是否有可能在C#中使用Regex类进行不区分大小写的匹配而不设置RegexOptions.IgnoreCase标志?不区分大小写正则表达式不使用RegexOptions枚举
我希望能够做的是在正则表达式本身定义我是否希望匹配操作以不区分大小写的方式完成。
我想这个表达式,taylor
,以匹配以下值:
- 泰勒
- 泰勒
- 泰勒
是否有可能在C#中使用Regex类进行不区分大小写的匹配而不设置RegexOptions.IgnoreCase标志?不区分大小写正则表达式不使用RegexOptions枚举
我希望能够做的是在正则表达式本身定义我是否希望匹配操作以不区分大小写的方式完成。
我想这个表达式,taylor
,以匹配以下值:
(?i)taylor
符合所有输入我pecified而不必设置RegexOptions.IgnoreCase标志。
要强制区分大小写,我可以做(?-i)taylor
。
它看起来像其他的选项包括:
i
,不区分大小写s
,单线模式m
,多行模式x
,自由间隔模式正如spoon16所说的,它是(?i)
。 MSDN具有regular expression options一个列表,它包括使用不区分大小写匹配的只是匹配的部分的示例:匹配不区分大小写
string pattern = @"\b(?i:t)he\w*\b";
这里的“T”,但其余的是大小写敏感的。如果您未指定子表达式,则为封闭组的其余部分设置该选项。
因此,对于你例如,你可以有:
string pattern = @"My name is (?i:taylor).";
这将匹配“我的名字是泰勒”,而不是“我叫泰勒”。
正如您已经发现的,(?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'
我如何可以将它添加到表达式如下:public const string Url = @“^(?:(?: https?| ftp):\/\ /)(?:\ S +(?:: \ S *)?@)?(?:(?!(?: 10 | 127):{3})|((\ \ d {1,3}?)((?: 169 \ 0.254 192 \ .168?!)?:\。\ d { 1,3}){2})(?172 \(?: 1 [6-9] | 2 \ d | 3 [0-1])(:?\ \ d {1,3}){ 2})(?:[1-9] \ d?| 1 \ d \ d | 2 [01] \ d | 22 [0-3])(?:?\(?: 1 \ d {1,2} | 2 [0-4] \ d | 25 0-5])){2}(:\(?:?[1-9] \ d | 1 \ d \ d | 2 [0-4] \ d | 25 [0-4]))| (:(:[AZ \ u00a1- \ uffff0-9] - *)* [AZ \ u00a1- \ uffff0-9] +?)(?:?\(:[AZ \ u00a1- \ uffff0-9] ???? - *)* [AZ \ u00a1- \ uffff0-9] +)*(:\(:[AZ \ u00a1- \ uffff] {2,}))\)(:: \ d { 2,5})(:[/#?] \ S *)$“;???? – Yovav 2017-11-14 00:53:08