[英]Match C# Unicode Identifier using Regex
使用.Net Regex模式匹配C#标识符(特别是属性或字段名称)的正确方法是什么?
背景。 我以前使用ASCII中心@“[_ a-zA-Z] [_ a-zA-Z0-9] *”但现在unicode大写和小写字符是合法的,例如“AboöДЖem”。 我应该如何将这些包含在模式中?
谢谢,马克斯
这是一个考虑了不允许的前导数字的版本:
^(?:((?!\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
根据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}]*
regex \\ w中预定义类解决的问题是否与öД匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.