regular expression to match exact word with boundries

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

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:

  1. test := `(?i)\b(co.)(?:\s|$)`
  2. re = regexp.MustCompile(test)
  3. 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来访问捕获组:

  1. package main
  2. import (
  3. "fmt"
  4. "regexp"
  5. )
  6. func main(){
  7. // your code goes here
  8. test := `(?i)\b(co.)(?:\s|$)`
  9. re := regexp.MustCompile(test)
  10. matches := re.FindAllStringSubmatch("co. is a secret shortcut ", -1)
  11. for _, match := range matches {
  12. fmt.Printf("'%s'", match[1])
  13. }
  14. }

输出:

  1. 'co.'

在ideone上查看演示

英文:

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

  1. package main
  2. import ( "fmt"
  3. "regexp"
  4. )
  5. func main(){
  6. // your code goes here
  7. test := `(?i)\b(co.)(?:\s|$)`
  8. re := regexp.MustCompile(test)
  9. matches := re.FindAllStringSubmatch("co. is a secret shortcut ", -1)
  10. for _, match := range matches {
  11. fmt.Printf("'%s'", match[1])
  12. }
  13. }

Output:

  1. '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:

确定