给定这样的代码:
str := "hi hey hello"
regexpr := `(?i)hello|hey|hi`
fmt.Println(regexp.MustCompile(regexpr).FindStringSubmatch(str))
它给出这样的结果:
[hi]
但我想得到一个
[hello]
作为结果。因为在我的情况下,“hello”是第一优先级,所以第二优先级是“hey”,然后是“hi”。我该如何实现?我只知道将关键字放入 slice 并循环播放的解决方案。但是使用单个正则表达式操作则不会。
是否可以使用单个正则表达式操作?
最佳答案
您应该记住,正则表达式引擎从左到右搜索匹配项。因此,“将优先级设置为替代项”意味着“让每个替代匹配项位于当前位置右侧的任何位置”。
你应该用
regexpr := `(?i).*?(hello)|.*?(hey)|.*?(hi)`
在这里,
.*?
将匹配除换行符以外的任何0个或多个字符,并且尽可能少。在代码中,使用regexp.MustCompile(regexpr).FindStringSubmatch(str)[1]
参见Go playground demo:
package main
import (
"fmt"
"regexp"
)
func main() {
str := "hi hey hello"
regexpr := `(?i).*?(hello)|.*?(hey)|.*?(hi)`
fmt.Println(regexp.MustCompile(regexpr).FindStringSubmatch(str)[1])
}
关于regex - 正则表达式找到具有优先顺序的匹配项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61836985/