Case insensitive Regex without using RegexOptions enumeration

后端 未结 3 1655
时光说笑
时光说笑 2020-11-30 00:53

Is it possible to do a case insensitive match in C# using the Regex class without setting the RegexOptions.IgnoreCase flag?

What I would like to be able to do is wit

相关标签:
3条回答
  • 2020-11-30 01:46

    As you already found out, (?i) is the in-line equivalent of RegexOptions.IgnoreCase.

    Just FYI, there are a few tricks you can do with it:

    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'
    

    And you can even combine flags like this: a(?mi-s)bc meaning:

    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'
    
    0 讨论(0)
  • 2020-11-30 01:48

    MSDN Documentation

    (?i)taylor matches all of the inputs I specified without having to set the RegexOptions.IgnoreCase flag.

    To force case sensitivity I can do (?-i)taylor.

    It looks like other options include:

    • i, case insensitive
    • s, single line mode
    • m, multi line mode
    • x, free spacing mode
    0 讨论(0)
  • 2020-11-30 01:48

    As spoon16 says, it's (?i). MSDN has a list of regular expression options which includes an example of using case-insensitive matching for just part of a match:

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

    Here the "t" is matched case-insensitively, but the rest is case-sensitive. If you don't specify a subexpression, the option is set for the rest of the enclosing group.

    So for your example, you could have:

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

    This would match "My name is TAYlor" but not "MY NAME IS taylor".

    0 讨论(0)
提交回复
热议问题