是否可以使用Regex类在C#中进行不区分大小写的匹配而不设置RegexOptions.IgnoreCase标志?
我希望能够做的是在正则表达式中定义我是否希望以不区分大小写的方式完成匹配操作.
我希望这个正则表达式taylor
匹配以下值:
Bar*_*ers 58
正如您已经发现的那样,(?i)
是在线等效的RegexOptions.IgnoreCase
.
仅供参考,你可以用它做一些技巧:
Regex:
a(?i)bc
Matches:
a # match the character 'a'
(?i) # enable case insensitive matching
b # match the character 'b' or 'B'
c # match the character 'c' or 'C'
Regex:
a(?i)b(?-i)c
Matches:
a # match the character 'a'
(?i) # enable case insensitive matching
b # match the character 'b' or 'B'
(?-i) # disable case insensitive matching
c # match the character 'c'
Regex:
a(?i:b)c
Matches:
a # match the character 'a'
(?i: # start non-capture group 1 and enable case insensitive matching
b # match the character 'b' or 'B'
) # end non-capture group 1
c # match the character 'c'
Run Code Online (Sandbox Code Playgroud)
你甚至可以组合这样的标志:a(?mi-s)bc
意思是:
a # match the character 'a'
(?mi-s) # enable multi-line option, case insensitive matching and disable dot-all option
b # match the character 'b' or 'B'
c # match the character 'c' or 'C'
Run Code Online (Sandbox Code Playgroud)
Jon*_*eet 26
正如勺子16说的那样(?i)
.MSDN有一个正则表达式选项列表,其中包含仅对匹配的一部分使用不区分大小写的匹配的示例:
string pattern = @"\b(?i:t)he\w*\b";
Run Code Online (Sandbox Code Playgroud)
这里"t"与大小写不匹配,但其余部分区分大小写.如果未指定子表达式,则会为封闭组的其余部分设置该选项.
所以对于你的例子,你可以:
string pattern = @"My name is (?i:taylor).";
Run Code Online (Sandbox Code Playgroud)
这将匹配"我的名字是泰勒"而不是"我的名字是泰勒".
归档时间: |
|
查看次数: |
46402 次 |
最近记录: |