2010-03-13 117 views
64

是否有可能在C#中使用Regex類進行不區分大小寫的匹配而不設置RegexOptions.IgnoreCase標誌?不區分大小寫正則表達式不使用RegexOptions枚舉

我希望能夠做的是在正則表達式本身定義我是否希望匹配操作以不區分大小寫的方式完成。

我想這個表達式,taylor,以匹配以下值:

  • 泰勒
  • 泰勒
  • 泰勒

回答

93

MSDN Documentation

(?i)taylor符合所有輸入我pecified而不必設置RegexOptions.IgnoreCase標誌。

要強制區分大小寫,我可以做(?-i)taylor

它看起來像其他的選項包括:

  • i,不區分大小寫
  • s,單線模式
  • m,多行模式
  • x,自由間隔模式
+0

我如何可以將它添加到表達式如下: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

24

正如spoon16所說的,它是(?i)。 MSDN具有regular expression options一個列表,它包括使用不區分大小寫匹配的只是匹配的部分的示例:匹配不區分大小寫

string pattern = @"\b(?i:t)he\w*\b"; 

這裏的「T」,但其餘的是大小寫敏感的。如果您未指定子表達式,則爲封閉組的其餘部分設置該選項。

因此,對於你例如,你可以有:

string pattern = @"My name is (?i:taylor)."; 

這將匹配「我的名字是泰勒」,而不是「我叫泰勒」。

47

正如您已經發現的,(?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' 
相關問題