正则表达式找到具有优先顺序的匹配项? [英] Regexp find a match with priority order?

查看:57
本文介绍了正则表达式找到具有优先顺序的匹配项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出这样的代码:

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

它给出了这样的结果:

[hi]

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

But I want to get a [hello] as a result. Because in my case 'hello' is first priority, second priority is 'hey', and then 'hi'. How can I achieve it ?

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

I only know the solution to put keywords in slice and loop it. But it would not with single regexp operation.

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

Is it possible to do with single regexp operation ?

推荐答案

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

You should bear in mind that regex engine searches for matches from left to right. Thus, to "set prioroty to an alternative" means "let each aternative match at any position to the right of the current location".

您应该使用

regexpr := `(?i).*?(hello)|.*?(hey)|.*?(hi)`

在这里,.*?将匹配除换行符以外的任何0个或多个字符,并且尽可能少.在代码中,使用

Here, .*? will match any 0 or more chars other than line break chars, as few as possible. In the code, use

regexp.MustCompile(regexpr).FindStringSubmatch(str)[1]

请参见去游乐场演示:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    str := "hi hey hello"
    regexpr := `(?i).*?(hello)|.*?(hey)|.*?(hi)`
    fmt.Println(regexp.MustCompile(regexpr).FindStringSubmatch(str)[1])
}

这篇关于正则表达式找到具有优先顺序的匹配项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆