不区分大小写的正则表达式,不使用RegexOptions枚举


76

是否可以使用Regex类在C#中进行不区分大小写的匹配,而无需设置RegexOptions.IgnoreCase标志?

我想做的是在正则表达式本身中定义我是否希望以不区分大小写的方式完成匹配操作。

我想要此正则表达式taylor匹配以下值:

  • 泰勒
  • 泰勒
  • 泰勒

Answers:


108

MSDN文档

(?i)taylor 匹配我指定的所有输入,而不必设置RegexOptions.IgnoreCase标志。

为了提高区分大小写,我可以做(?-i)taylor

看起来其他选项包括:

  • i, 不区分大小写
  • s,单行模式
  • m,多线模式
  • x,自由间距模式

59

正如您已经发现的,(?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'

27

就像spoon16所说的那样(?i)。MSDN提供了一个正则表达式选项列表,其中包括一个仅对部分匹配使用不区分大小写的匹配的示例:

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

此处的“ t”不区分大小写,其余的则区分大小写。如果未指定子表达式,则会为其余的封闭组设置该选项。

因此,对于您的示例,您可能需要:

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

这将与“我的名字是TAYlor”相匹配,而不是“我的名字是taylor”。

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.