英文:
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 '(?<=\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("(?:\\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)
Output:
bar 4
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论