How do I do a case insensitive regular expression in Go?

后端 未结 4 1137
粉色の甜心
粉色の甜心 2020-12-12 18:36

Now, of course, I could write my regular expression to handle both cases, such as regexp.Compile(\"[a-zA-Z]\"), but my regular expression is constructed from a

相关标签:
4条回答
  • 2020-12-12 19:09

    You can add a (?i) at the beginning of the pattern to make it case insensitive.

    Reference

    0 讨论(0)
  • 2020-12-12 19:24

    You can set a case-insensitive flag as the first item in the regex.

    You do this by adding "(?i)" to the beginning of a regex.

    reg, err := regexp.Compile("(?i)"+strings.Replace(s.Name, " ", "[ \\._-]", -1))
    

    For a fixed regex it would look like this.

    r := regexp.MustCompile(`(?i)CaSe`)
    

    For more information about flags, search the regexp/syntax package documentation (or the syntax documentation) for the term "flags".

    0 讨论(0)
  • 2020-12-12 19:30

    I'm not too familiar with Go, but according to this example: http://play.golang.org/p/WgpNhwWWuW

    You need to prefix your regex statement with (?i)

    0 讨论(0)
  • 2020-12-12 19:36

    Use the i flag. Quoting the tip documentation:

    Grouping:

    (re)           numbered capturing group
    (?P<name>re)   named & numbered capturing group
    (?:re)         non-capturing group
    (?flags)       set flags within current group; non-capturing
    (?flags:re)    set flags during re; non-capturing
    

    Flag syntax is xyz (set) or -xyz (clear) or xy-z (set xy, clear z). The flags are:

    i              case-insensitive (default false)
    m              multi-line mode: ^ and $ match begin/end line in addition to begin/end text (default false)
    s              let . match \n (default false)
    U              ungreedy: swap meaning of x* and x*?, x+ and x+?, etc (default false)
    
    0 讨论(0)
提交回复
热议问题