regular expression to match exact word with boundries

huangapple go评论85阅读模式
英文:

regular expression to match exact word with boundries

问题

我正在使用golang的正则表达式来匹配具有边界的精确单词,例如"apple","co.",我不能简单地使用\b,因为单词可能在末尾有非字母数字字符,就像例子中的"co."一样。

我尝试了以下代码:

test := (?i)\b(co.)(?:\s|$)
re = regexp.MustCompile(test)
matches = re.FindAllString("co. is a secret shortcut ", -1)

但是这会给我返回"co. ",我想直接得到"co.",我该如何调整我的正则表达式来实现这一点。

提前感谢。

英文:

I am using golang regex to match an exact word with boundaries, for example "apple", "co.", I cannot simply use \b, because the word can have non alphanumeric char in the end, like the example "co."

I try something like:

test := `(?i)\b(co.)(?:\s|$)`
re = regexp.MustCompile(test)
matches = re.FindAllString("co. is a secret shortcut ", -1)

but this will give me "co. ", I would like to directly get "co.", how can I adjust my regex to achieve it.

Thanks in advance

答案1

得分: 2

你可以使用FindAllStringSubmatch来访问捕获组:

package main
import (
    "fmt"
    "regexp"
)

func main(){
    // your code goes here
    test := `(?i)\b(co.)(?:\s|$)`
    re := regexp.MustCompile(test)
    matches := re.FindAllStringSubmatch("co. is a secret shortcut ", -1)
    for _, match := range matches {
        fmt.Printf("'%s'", match[1])
    }
}

输出:

'co.'

在ideone上查看演示

英文:

You could use FindAllStringSubmatch to give you access to the capture group:

package main
import ( "fmt"
        "regexp"
        )

func main(){
	// your code goes here
	test := `(?i)\b(co.)(?:\s|$)`
	re := regexp.MustCompile(test)
	matches := re.FindAllStringSubmatch("co. is a secret shortcut ", -1)
	for _, match := range matches {
		fmt.Printf("'%s'", match[1])
	}
}

Output:

'co.'

Demo on ideone

huangapple
  • 本文由 发表于 2023年5月27日 12:51:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/76345360.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定