VB.Net字符串转义语法糖

VB.Net字符串转义语法糖

地狱门神

 

众所周知,VB中没有C#的字符串转义语法。

C#中可以写

 

string s = "This is a string with newline.\n";

而VB中只能写

Dim s = "This is a string with newline." & vbLf

 

人们渴望一个和C#中的"@"字符串正好相反的语法:

string s = @"This is a string with '\n' literal.\n";
Dim s = @"This is a string with newline.\n"

 

 但是,这种语法还没有被加入。

 

于是,我通过使用扩展函数,实现了比较接近的语法。

Dim s = "This is a string with newline.\n".Descape

另外,还对String.Format进行了类似处理

Dim s2 = "This is a string that is {0}".Formats("formated.")

 

具体实现如下:

'==========================================================================
'
'
  File:        StringDescape.vb
'
  Description: VB.Net字符串转义语法糖 <Visual Basic 9>
'
  Version:     2008.09.28.
'
  (cc)         F.R.C. 按照 Creative Commons Public Domain Dedication License 捐献
'
               http://creativecommons.org/licenses/publicdomain/
'
'
==========================================================================

Imports System
Imports System.Collections.Generic
Imports System.Text
Imports System.Text.RegularExpressions
Imports System.Runtime.CompilerServices
Imports Microsoft.VisualBasic

''' <summary>字符串转义</summary>
Public Module StringDescape

    
''' <summary>字符串反转义函数</summary>
    
''' <remarks>
    
''' \0 与null \u0000 匹配
    
''' \a 与响铃(警报)\u0007 匹配 
    
''' \b 与退格符 \u0008 匹配
    
''' \t 与 Tab 符 \u0009 匹配 
    
''' \r 与回车符 \u000D 匹配
    
''' \v 与垂直 Tab 符 \u000B 匹配
    
''' \f 与换页符 \u000C 匹配
    
''' \n 与换行符 \u000A 匹配
    
''' \e 与 Esc 符 \u001B 匹配
    
''' \x?? 与 \u00?? 匹配
    
''' \u???? 与对应的Unicode字符对应
    
''' </remarks>

    <Extension()> Public Function Descape(ByVal This As StringAs String
        
Dim m = r.Match(This)
        
If Not m.Success Then Throw New InvalidCastException

        
Dim ss As New SortedList(Of IntegerString)
        
For Each c As Capture In m.Groups.Item("SingleEscape").Captures
            ss.Add(c.Index, SingleEscapeDict(c.Value))
        
Next
        
For Each c As Capture In m.Groups.Item("UnicodeEscape").Captures
            ss.Add(c.Index, 
ChrW(CInt("&H" & c.Value)))
        
Next
        
For Each c As Capture In m.Groups.Item("ErrorEscape").Captures
            
Throw New ArgumentException("ErrorEscape: Ch " & (c.Index + 1& " " & c.Value)
        
Next
        
For Each c As Capture In m.Groups.Item("Normal").Captures
            ss.Add(c.Index, c.Value)
        
Next

        
Dim sb As New StringBuilder
        
For Each s In ss.Values
            sb.Append(s)
        
Next

        
Return sb.ToString
    
End Function


    
''' <summary>将指定的 String 中的格式项替换为指定的 Object 实例的值的文本等效项。</summary>
    <Extension()> Public Function Formats(ByVal This As StringByVal arg0 As ObjectAs String
        
Return String.Format(This, arg0)
    
End Function

    
''' <summary>将指定的 String 中的格式项替换为两个指定的 Object 实例的值的文本等效项。</summary>
    <Extension()> Public Function Formats(ByVal This As StringByVal arg0 As ObjectByVal arg1 As ObjectAs String
        
Return String.Format(This, arg0, arg1)
    
End Function

    
''' <summary>将指定的 String 中的格式项替换为三个指定的 Object 实例的值的文本等效项。</summary>
    <Extension()> Public Function Formats(ByVal This As StringByVal arg0 As ObjectByVal arg1 As ObjectByVal arg2 As ObjectAs String
        
Return String.Format(This, arg0, arg1, arg2)
    
End Function

    
''' <summary>将指定 String 中的格式项替换为指定数组中相应 Object 实例的值的文本等效项。</summary>
    <Extension()> Public Function Formats(ByVal This As StringByVal ParamArray args As Object()) As String
        
Return String.Format(This, args)
    
End Function

    
''' <summary>将指定 String 中的格式项替换为指定数组中相应 Object 实例的值的文本等效项。指定的参数提供区域性特定的格式设置信息。</summary>
    <Extension()> Public Function Formats(ByVal This As StringByVal provider As IFormatProvider, ByVal ParamArray args As Object()) As String
        
Return String.Format(provider, This, args)
    
End Function



    
Private ReadOnly Property SingleEscapeDict() As Dictionary(Of StringString)
        
Get
            
Static d As Dictionary(Of StringString)
            
If d IsNot Nothing Then Return d
            d 
= New Dictionary(Of StringString)
            d.Add(
"\""\"'backslash
            d.Add("0"ChrW(0)) 'null
            d.Add("a"ChrW(7)) 'alert (beep)
            d.Add("b"ChrW(8)) 'backspace
            d.Add("f"ChrW(&HC)) 'form feed
            d.Add("n"ChrW(&HA)) 'newline (lf)
            d.Add("r"ChrW(&HD)) 'carriage return (cr) 
            d.Add("t"ChrW(9)) 'horizontal tab 
            d.Add("v"ChrW(&HB)) 'vertical tab
            Return d
        
End Get
    
End Property

    
Private ReadOnly Property SingleEscapes() As String
        
Get
            
Static s As String
            
If s IsNot Nothing Then Return s
            
Dim Chars As New List(Of String)
            
For Each c In "\0abfnrtv"
                Chars.Add(Regex.Escape(c))
            
Next
            s 
= "\\(?<SingleEscape>" & String.Join("|", Chars.ToArray) & ")"
            
Return s
        
End Get
    
End Property

    
Private UnicodeEscapes As String = "\\[uU](?<UnicodeEscape>[0-9A-Fa-f]{4})|\\x(?<UnicodeEscape>[0-9A-Fa-f]{2})"
    
Private ErrorEscapes As String = "(?<ErrorEscape>\\)"
    
Private Normal As String = "(?<Normal>.)"

    
Private r As New Regex("^" & "(" & SingleEscapes & "|" & UnicodeEscapes & "|" & ErrorEscapes & "|" & Normal & ")*" & "$", RegexOptions.ExplicitCapture)
End Module

 

完整代码可从下面下载

https://files.cnblogs.com/Rex/StringDescape.rar

 

编译环境要求VS2008。运行时至少要.Net Framework 2.0 + System.Core.dll。

 

posted @ 2008-09-28 14:21  地狱门神  阅读(2567)  评论(0编辑  收藏  举报