【问题标题】:negative lookahead负前瞻
【发布时间】:2019-03-02 10:23:09
【问题描述】:

我正在尝试编写一个匹配除一个单词(本例中为 themagicword)之外的任何内容的正则表达式,来自 perl/python 世界我会用否定的前瞻来做到这一点:^(?!themagicword).*
我如何在 golang 中实现这一点,因为这在 golang 中似乎不起作用。

【问题讨论】:

  • stdlib 正则表达式引擎不支持前瞻。
  • 如果您能够使用 CGO,您可以使用多个 pcre 软件包 like this one 之一。只需谷歌“pcre golang”或其他东西
  • 不应该是:^(?!.*themagicword).*^(?!themagicword$).* 吗?而且$haystack !~ /themagicword/ 不是更有效率吗?
  • 听起来你只需要if input != "themagicword" { ... },没有正则表达式。或者if !strings.HasPrefix(input, "themagicword") { ... }.

标签: regex go


【解决方案1】:

“匹配除一个单词之外的任何内容”相当于“匹配(非单词)”,相当于“不匹配(匹配单词)”。所以只需匹配您要排除的单词,然后返回逆:

hasmagic, _ := regexp.MatchString("themagicword", "haystack")
matched := !hasmagic

【讨论】:

  • @RamGhadiyaram 这样吗?
猜你喜欢
  • 2016-07-27
  • 1970-01-01
  • 2011-01-15
  • 2020-07-03
  • 1970-01-01
  • 2021-10-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多