正则表达式在Go中不匹配

问题描述

我有一个与Go不匹配的正则表达式。

但是在正则表达式游戏场中,它匹配得很好:https://regex101.com/r/VNDXcQ/2

它与JS注释匹配。

代码如下:

comment := "// fallback response. For more information contact support"
re := regexp.MustCompile(`/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm`)
matches := re.MatchString(comment)
fmt.Println(matches) // false

为什么会这样?

解决方法

有两个主要问题:

  • 您正在使用正则表达式文字作为字符串正则表达式模式。这意味着,您需要通过将其转换为/内联修饰符
  • ,将第一个m和最后一个(?m)以及“移动” MatchString标志删除到模式
  • 您只能将第一个匹配项与g匹配(因为标志不能与正则表达式模式一起传递,并且re := regexp.MustCompile(`(?m)/\*[\s\S]*?\*/|([^\\:]|^)//.*`) matches := re.FindAllString(comment,-1) 标志“不支持”)。您需要使用FindAllString来获取所有匹配项。

您可以通过以下方式解决此问题

/

注意enum class Animal { Cat,Dog,Fish}; float GetMaxSpeed(Animal a) { switch (a) { case Animal::Cat: return 30; case Animal::Dog: return 40; case Animal::Fish: return 15; } } string GetGermanTranslation(Animal a) { switch (a) { case Animal::Cat: return "Katze"; case Animal::Dog: return "Hund"; case Animal::Fish: return "Fische"; } } 不是特殊字符,因此不需要转义。

请参见Go playground

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...