dping1968 2019-01-08 15:48
浏览 369
已采纳

Go中跨越多行的正则表达式[关闭]

Is it possible in Go to break a complex regular expression using multiple lines? It would help a lot to create a more readable code.

For example in Scala, Ruby, JavaScript it is possible to use x flag:

x — Free-spacing and line comments (aka extended mode)

And it allows to write regular expression like:

  TAXON_CONCEPTS2 = /\s+
                     (\(?s\.\s?s\.|
                     \(?s\.\s?l\.|
                     \(?s\.\s?str\.|
                     \(?s\.\s?lat\.|
                    sec\.|sec|near)\b.*$/x

I would like to achieve similar code in Go instead of:

var taxonConceptsRe2 = regexp.MustCompile(`(,\s*|\s+)(\(?s\.\s?s\.|\(?s\.\s?l\.|\(?s\.\s?str\.|\(?s\.\s?lat\.).*$`)
  • 写回答

2条回答 默认 最新

  • dtntjwkl83750 2019-01-08 16:09
    关注

    You have a few options to improve readability of a regular expression like this.

    1. Split the string:

      pattern := `(,\s*|\s+)` +
          `(\(?s\.\s?s\.|` +
          `\(?s\.\s?l\.|` +
          `\(?s\.\s?str\.|` +
          `\(?s\.\s?lat\.).*$`
      
    2. Pre-parse the string:

      pattern := strings.Replace(`\s+
                       (\(?s\.\s?s\.|
                       \(?s\.\s?l\.|
                       \(?s\.\s?str\.|
                       \(?s\.\s?lat\.|
                      sec\.|sec|near)\b.*$`,
              "
                      ", "", -1)
      

      If you choose this approach, you'll probably want to build a function to do this for you, and to be a bit more robust.

    3. Don't use a regexp. (Obviously not always ideal, but regexes are often very overused, so do this one if it makes sense.)

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

报告相同问题?

悬赏问题

  • ¥15 iOS 自定义输入法-第三方输入法
  • ¥15 很想要一个很好的答案或提示
  • ¥15 扫描项目中发现AndroidOS.Agent、Android/SmsThief.LI!tr
  • ¥15 怀疑手机被监控,请问怎么解决和防止
  • ¥15 Qt下使用tcp获取数据的详细操作
  • ¥15 idea右下角设置编码是灰色的
  • ¥15 全志H618ROM新增分区
  • ¥15 在grasshopper里DrawViewportWires更改预览后,禁用电池仍然显示
  • ¥15 NAO机器人的录音程序保存问题
  • ¥15 C#读写EXCEL文件,不同编译