Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Match C# Unicode Identifier using Regex

What is the right way to match a C# identifier, specifically a property or field name, using .Net Regex patterns?

Background. I used to use the ASCII centric @"[_a-zA-Z][_a-zA-Z0-9]*" But now unicode uppercase and lowercase characters are legit, e.g. "AboöДЖem". How should I include these in the pattern?

Thanks, Max

like image 546
Max Yaffe Avatar asked Dec 09 '10 16:12

Max Yaffe


2 Answers

Here's a version that takes into account the disallowed leading digits:

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

And here are some tests in 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
like image 63
Damian Powell Avatar answered Oct 26 '22 23:10

Damian Powell


According to http://msdn.microsoft.com/en-us/library/aa664670.aspx, and ignoring the keyword and unicode-escape-sequence stuff,

@?[_\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}]*
like image 40
kennytm Avatar answered Oct 27 '22 00:10

kennytm