使用Regex匹配C#Unicode标识符

Max*_*ffe 5 c# regex unicode character-properties

使用.Net Regex模式匹配C#标识符(特别是属性或字段名称)的正确方法是什么?

背景.我以前使用ASCII中心@"[_ a-zA-Z] [_ a-zA-Z0-9]*"但现在unicode大写和小写字符是合法的,例如"AboöДЖem".我应该如何将这些包含在模式中?

谢谢,马克斯

Dam*_*ell 8

这是一个考虑了不允许的前导数字的版本:

^(?:((?!\d)\w+(?:\.(?!\d)\w+)*)\.)?((?!\d)\w+)$
Run Code Online (Sandbox Code Playgroud)

以下是PowerShell中的一些测试:

[regex]$regex = '(?x:
    ^                        # Start of string
    (?:
        (                    # Namespace
            (?!\d)\w+        #   Top-level namespace
            (?:\.(?!\d)\w+)* #   Subsequent namespaces
        )
        \.                   # End of namespaces period
    )?                       # Namespace is optional
    ((?!\d)\w+)              # Class name
    $                        # End of string
)'
@(
    'System.Data.Doohickey'
    '_1System.Data.Doohickey'
    'System.String'
    'System.Data.SqlClient.SqlConnection'
    'DoohickeyClass'
    'Stackoverflow.Q4400348.Aboö??em'
    '1System.Data.Doohickey' # numbers not allowed at start of namespace
    'System.Data.1Doohickey' # numbers not allowed at start of class
    'global::DoohickeyClass' # "global::" not part of actual namespace
) | %{
    ($isMatch, $namespace, $class) = ($false, $null, $null)
    if ($_ -match $regex) {
        ($isMatch, $namespace, $class) = ($true, $Matches[1], $Matches[2])
    }
    new-object PSObject -prop @{
        'IsMatch'   = $isMatch
        'Name'      = $_
        'Namespace' = $namespace
        'Class'     = $class
    }
} | ft IsMatch, Name, Namespace, Class -auto
Run Code Online (Sandbox Code Playgroud)


ken*_*ytm 5

根据http://msdn.microsoft.com/en-us/library/aa664670.aspx,忽略关键字unicode-escape-sequence的东西,

@?[_\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}][\p{Lu}\p{Ll}\p{Lt}\p{Lm}\p{Lo}\p{Nl}\p{Mn}\p{Mc}\p{Nd}\p{Pc}\p{Cf}]*
Run Code Online (Sandbox Code Playgroud)

  • 这是编译器从源头确定它的方式,以防万一有人感兴趣:https://github.com/dotnet/roslyn/blob/e123a4207123d5df8c45fb1caba0fb3acbae0e00/src/Compilers/Core/Portable/InternalUtilities/UnicodeCharacterUtilities.cs -L130 (2认同)

rer*_*run -3

正则表达式 \\w 将匹配 \xc3\xb6\xd0\x94 中的预定义类解决了该问题吗?

\n

  • 您不能只使用 @"\w+" 来匹配标识符 - 它会包含以数字开头的单词 - 例如,它会匹配“12abc”,这是一个无效标识符。我建议 @"[\w-[0-9]]\w*" 作为解决方案。 (2认同)