英文:
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.'
英文:
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.'
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论