dongming5444 2013-03-10 19:19
浏览 1325
已采纳

如何在Go中执行不区分大小写的正则表达式?

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.

  • 写回答

4条回答 默认 最新

  • douquqiang1513 2013-03-10 19:23
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(3条)

报告相同问题?

悬赏问题

  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP