101

现在,当然,我可以编写正则表达式来处理这两种情况,例如regexp.Compile("[a-zA-Z]"),但是我的正则表达式是由用户给出的字符串构造的:

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

s.Name名字在哪里。这可能类似于“西北偏北”。现在,对我来说最明显的解决方案是遍历每个字符s.Name并为每个字母写 '[nN]':

for i := 0; i < len(s.Name); i++ {
  if s.Name[i] == " " {
    fmt.Fprintf(str, "%s[ \\._-]", str);
  } else {
    fmt.Fprintf(str, "%s[%s%s]", str, strings.ToLower(s.Name[i]), strings.ToUpper(s.Name[i]))
  }
}

但我觉得这是一个相当不优雅的解决方案。速度并不是真正的问题,但我需要知道是否有其他方法。

4

4 回答 4

208

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".

于 2013-03-10T19:23:17.963 回答
34

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

Reference

于 2013-03-10T19:22:37.160 回答
8

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)

于 2013-03-10T19:22:48.563 回答
4

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)
于 2013-03-10T19:24:16.320 回答