Regex: ignore case sensitivity

后端 未结 13 1816
孤城傲影
孤城傲影 2020-11-22 06:11

How can I make the following regex ignore case sensitivity? It should match all the correct characters but ignore whether they are lower or uppercase.

G[a-b]         


        
相关标签:
13条回答
  • 2020-11-22 06:36

    As I discovered from this similar post (ignorecase in AWK), on old versions of awk (such as on vanilla Mac OS X), you may need to use 'tolower($0) ~ /pattern/'.

    IGNORECASE or (?i) or /pattern/i will either generate an error or return true for every line.

    0 讨论(0)
  • 2020-11-22 06:40

    JavaScript

    If you want to make it case insensitive just add i at the end of regex:

    'Test'.match(/[A-Z]/gi) //Returns ["T", "e", "s", "t"]

    Without i

    'Test'.match(/[A-Z]/g) //Returns ["T"]

    0 讨论(0)
  • 2020-11-22 06:44

    In Java, Regex constructor has

    Regex(String pattern, RegexOption option)
    

    So to ignore cases, use

    option = RegexOption.IGNORE_CASE
    
    0 讨论(0)
  • 2020-11-22 06:45

    Just for the sake of completeness I wanted to add the solution for regular expressions in C++ with Unicode:

    std::tr1::wregex pattern(szPattern, std::tr1::regex_constants::icase);
    
    if (std::tr1::regex_match(szString, pattern))
    {
    ...
    }
    
    0 讨论(0)
  • 2020-11-22 06:50

    Assuming you want the whole regex to ignore case, you should look for the i flag. Nearly all regex engines support it:

    /G[a-b].*/i
    
    string.match("G[a-b].*", "i")
    

    Check the documentation for your language/platform/tool to find how the matching modes are specified.

    If you want only part of the regex to be case insensitive (as my original answer presumed), then you have two options:

    1. Use the (?i) and [optionally] (?-i) mode modifiers:

      (?i)G[a-b](?-i).*
      
    2. Put all the variations (i.e. lowercase and uppercase) in the regex - useful if mode modifiers are not supported:

      [gG][a-bA-B].*
      

    One last note: if you're dealing with Unicode characters besides ASCII, check whether or not your regex engine properly supports them.

    0 讨论(0)
  • 2020-11-22 06:50

    regular expression for validate 'abc' ignoring case sensitive

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