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

2024-09-29 20:28:10 发布

您现在位置:Python中文网/ 问答频道 /正文

鉴于这样一个准则:

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

它给出了这样的结果:

[hi]

但是我想得到一个[hello]作为结果。因为在我的例子中,“你好”是第一优先级,第二优先级是“嗨”,然后是“嗨”。我怎样才能做到呢

我只知道将关键字放入切片并循环的解决方案。但它不会使用单个regexp操作

可以使用单个regexp操作吗


Tags: hello切片关键字解决方案hi例子regexpprintln
1条回答
网友
1楼 · 发布于 2024-09-29 20:28:10

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

你应该使用

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])
}

相关问题 更多 >

    热门问题