Match proceeding word without look ahead in Go

huangapple go评论88阅读模式
英文:

Match proceeding word without look ahead in Go

问题

我正在尝试从查询字符串中提取表名(例如,'select foo from bar limit 10' 应该返回 'bar')。

我相信 '(?<=\bfrom\s)(\w+)' 是我正在寻找的内容,但它在 Go 的正则表达式包中不受支持。(http://play.golang.org/p/MJ3DUk6uuC)

英文:

I am trying to retrieve the table from a query string (eg. 'select foo from bar limit 10' should return 'bar').

I believe '(?&lt;=\bfrom\\s)(\\w+)' is what I was looking for but it is unsupported by Go regexp package. (http://play.golang.org/p/MJ3DUk6uuC)

答案1

得分: 3

你仍然可以检测到'from xxx',而不需要查看**re2**不支持的前瞻语法。由于你会捕获到'from',所以你需要从结果中将其移除。

请参见playground

r := regexp.MustCompile("(?:\\bfrom\\s)(\\w+)")
res := r.FindAllString(strings.ToLower("select foo from bar limit 10"), 1)
if len(res) != 1 {
    panic("unable")
}
i := strings.LastIndex(res[0], " ")
fmt.Println(res[0][i+1:], i)

输出:

bar 4
英文:

You still can detect 'from xxx', without looking the lookahead syntax not supported by re2.
Since you would then capture 'from ', you need to remove it from the result.

See playground:

r := regexp.MustCompile(&quot;(?:\\bfrom\\s)(\\w+)&quot;)
res := r.FindAllString(strings.ToLower(&quot;select foo from bar limit 10&quot;), 1)
if len(res) != 1 {
	panic(&quot;unable&quot;)
}
i := strings.LastIndex(res[0], &quot; &quot;)
fmt.Println(res[0][i+1:], i)

Output:

bar 4

huangapple
  • 本文由 发表于 2015年1月7日 03:57:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/27806236.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定