5

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

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

谢谢,马克斯

4

3 回答 3

8

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

^(?:((?!\d)\w+(?:\.(?!\d)\w+)*)\.)?((?!\d)\w+)$

以下是 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
于 2012-10-19T18:40:02.013 回答
6

根据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}]*
于 2010-12-09T16:21:29.707 回答
-3

正则表达式中的预定义类是否解决了该问题 \w 将匹配 öД.

于 2010-12-09T16:23:38.347 回答