如何在Go中执行不区分大小写的正则表达式? [英] How do I do a case insensitive regular expression in Go?

查看:478
本文介绍了如何在Go中执行不区分大小写的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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



<其中 s.Name 是名称。这可能是'北西北'。现在,对我来说最明显的解决方案是遍历每个字母 s.Name 并为每个字母写'[nN]':

  for i:= 0;我< 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]))
}
}

但我觉得这是一种宁静非优雅的解决方案。速度不是真正的问题,但我需要知道是否有其他方法。 您可以设置不区分大小写标志作为正则表达式中的第一项。



您可以通过将(?i)添加到

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

对于一个固定的正则表达式它看起来像这样。

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

有关标志的更多信息,请搜索的术语旗帜。


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 string given by the user:

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

Where s.Name is the name. Which could be something like 'North by Northwest'. Now, the most apparent solution to me would be to walk through each character of s.Name and write '[nN]' for each letter:

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]))
  }
}

But I feel this is a rather non-elegant solution. Speed is not really a concern, but I need to know if there is another way.

解决方案

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 syntax documentation for the term "flags".

这篇关于如何在Go中执行不区分大小写的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆