【问题标题】:Regex for matching everything until first occurence of string in Golang flavor正则表达式匹配所有内容,直到第一次出现 Golang 风格的字符串
【发布时间】:2019-05-09 20:04:54
【问题描述】:

我有以下字符串:

我的名字-host1.host2.host3.com:80

我正在寻找一个匹配所有内容的正则表达式,直到字符串 -host1.host2.host3.com:80,即结果应为:

我的名字

我当前在 JavaScript 中的正则表达式似乎正在工作。问题是我需要这个“Golang 风格”的正则表达式。

https://regex101.com/r/ebSTuq/1

将它切换到 Golang 时,我得到了这个带有模式错误的正则表达式:
.*(?=\Q-host1.host2.host3.com:80\E)

前面的记号是不可量化的。

【问题讨论】:

  • 使用(.*?)-host1\.host2\.host3\.com:80。或者可能只是^[^-]+-[^-]+
  • Golang的re2不支持lookarounds,可以查看支持的语法here

标签: regex


【解决方案1】:

Go 正则表达式引擎是 RE2,RE2does not support lookarounds

实际上,您不需要前瞻:在开始时使用非贪婪点模式,将其捕获到第 1 组,然后按原样使用模式的其余部分来检查右手上下文:

str := `my-name-host1.host2.host3.com:80`
re := regexp.MustCompile(`(.*?)-host1\.host2\.host3\.com:80`)
match := re.FindStringSubmatch(str)
fmt.Println(match[1]) 

输出:my-name,见Go demo

注意FindStringSubmatch function 的使用,它允许访问捕获的子字符串。

另外,请参阅Go regex demo

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-19
    相关资源
    最近更新 更多