Regexp是否找到具有优先顺序的匹配项?

问题描述 投票:0回答:1

给出这样的代码:

str := "hi hey hello"
regexpr := `(?i)hello|hey|hi`
fmt.Println(regexp.MustCompile(regexpr).FindStringSubmatch(str))

它给出这样的结果:

[hi]

但是我想得到一个[hello]。因为在我的情况下,“ hello”是第一优先级,所以第二优先级是“ hey”,然后是“ hi”。我该如何实现?

我只知道将关键字放入切片并循环处理的解决方案。但是使用单个正则表达式操作则不会。

是否可以使用单个正则表达式操作?

regex go
1个回答
0
投票

您应该记住,正则表达式引擎从左到右搜索匹配项。因此,“将优先级设置为替代项”意味着“让每个替代匹配项位于当前位置右侧的任何位置”。

您应该使用

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])
}
© www.soinside.com 2019 - 2024. All rights reserved.