Golang中使用正则表达式进行字符串搜索
Golang中使用正则表达式进行字符串搜索 我正在做一个Codewar的题目,想要只匹配数字,但排除字母数字组合。
Boston Celtics 112 Philadelphia 76ers 95
r := regexp.MustCompile(`[0-9]+`)
提前感谢
4 回复
找到了解决方案
[^a-zA-Z\s]+\b
更多关于Golang中使用正则表达式进行字符串搜索的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
感谢回复。
从这个字符串 Boston Celtics 112 Philadelphia 76ers 95 中,我试图只获取 112 & 95,并排除 76ers。
我对正则表达式还很陌生,但我得出了这个 [^a-zA-Z\s]+\b,它可以消除所有字母和字母数字,只留下数字。
根据你的需求,要匹配纯数字但排除字母数字组合,可以使用单词边界 \b 来确保匹配独立的数字。你当前的正则表达式 [0-9]+ 会匹配字符串中的所有数字序列,包括字母数字组合中的数字部分(例如 “76ers” 中的 “76”)。为了避免这种情况,可以在正则表达式的两端添加 \b。
以下是修改后的正则表达式:
r := regexp.MustCompile(`\b[0-9]+\b`)
或者使用 \d 作为数字的简写:
r := regexp.MustCompile(`\b\d+\b`)
这样,正则表达式只会匹配独立的数字序列,而不会匹配字母数字组合中的数字部分。
示例代码:
package main
import (
"fmt"
"regexp"
)
func main() {
text := "Boston Celtics 112 Philadelphia 76ers 95"
r := regexp.MustCompile(`\b\d+\b`)
matches := r.FindAllString(text, -1)
fmt.Println(matches) // 输出: [112 95]
}
在这个示例中,正则表达式 \b\d+\b 只会匹配独立的数字 “112” 和 “95”,而不会匹配 “76ers” 中的 “76”。


