Max*_*ffe 5 c# regex unicode character-properties
使用.Net Regex模式匹配C#标识符(特别是属性或字段名称)的正确方法是什么?
背景.我以前使用ASCII中心@"[_ a-zA-Z] [_ a-zA-Z0-9]*"但现在unicode大写和小写字符是合法的,例如"AboöДЖem".我应该如何将这些包含在模式中?
谢谢,马克斯
这是一个考虑了不允许的前导数字的版本:
^(?:((?!\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)
根据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)
rer*_*run -3
正则表达式 \\w 将匹配 \xc3\xb6\xd0\x94 中的预定义类解决了该问题吗?
\n| 归档时间: |
|
| 查看次数: |
5860 次 |
| 最近记录: |