是否可以使用Regex类在C#中进行不区分大小写的匹配,而无需设置RegexOptions.IgnoreCase标志?
我想做的是在正则表达式本身中定义我是否希望以不区分大小写的方式完成匹配操作。
我想要此正则表达式taylor
匹配以下值:
- 泰勒
- 泰勒
- 泰勒
是否可以使用Regex类在C#中进行不区分大小写的匹配,而无需设置RegexOptions.IgnoreCase标志?
我想做的是在正则表达式本身中定义我是否希望以不区分大小写的方式完成匹配操作。
我想要此正则表达式taylor
匹配以下值:
Answers:
(?i)taylor
匹配我指定的所有输入,而不必设置RegexOptions.IgnoreCase标志。
为了提高区分大小写,我可以做(?-i)taylor
。
看起来其他选项包括:
i
, 不区分大小写s
,单行模式m
,多线模式x
,自由间距模式正如您已经发现的,(?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'
您甚至可以组合这样的标志: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'