Unicode Conformance Identifier for C # using Regex

What is the correct way to match a C # identifier, in particular a property or field name, using .Net Regex templates?

Background. I used to use the ASCII center @ "[_ a-zA-Z] [_ a-zA-Z0-9] *" But now, unicode characters in upper and lower case are valid, for example. "AboöJem". How to include them in a template?

Thanks Max

+5
source share
3 answers

Whether this problem is solved by using the predefined classes in regex \ w will correspond to ö.

+1
source

Here's a version that takes into account forbidden leading numbers:

^(?:((?!\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
+7

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}]*
+5
source

All Articles