我正在尝试使用golang regexp来查找重复的数字。这是我试图找到长度为8的重复数字。我试图遵循Regex to find repeating numbers的建议
testString := "11111111"
repetitive := `^(\d)\\1{8}$`
repetitiveR := regexp.MustCompile(repetitive)
if repetitiveR.MatchString(testString) {
fmt.Println("Match")
} else {
fmt.Println("No match")
}
它总是给我结果“不匹配”。另一种有效的方法是繁琐的
testString := "11111111"
repetitive := `^(0{8})|(1{8})|(2{8})|(3{8})|(4{8})|(5{8})|(6{8})|(7{8})|(8{8})|(9{8})$`
repetitiveR := regexp.MustCompile(repetitive)
if repetitiveR.MatchString(testString) {
fmt.Println("Match")
} else {
fmt.Println("No match")
}
输出:匹配
有什么建议
如果你需要在字符串的开头准确地捕获相同数字的八个重复,那么这应该有效:
package main
import (
"fmt"
"regexp"
)
func main() {
testString := "11111111"
repetitive := "^0{8}$|^1{8}$|^2{8}$|^3{8}$|^4{8}$|^5{8}$|^6{8}$|^7{8}$|^8{8}$|^9{8}$"
repetitiveR := regexp.MustCompile(repetitive)
if repetitiveR.MatchString(testString) {
fmt.Println("Match")
} else {
fmt.Println("No match")
}
}
注意:例如,你的cubersome regexp会捕获8个以上的数字,所以我已经纠正了一下。
来自official GitHub和评论中提到的:
RE2不支持仅知道存在回溯解的构造。因此,不支持反向引用和环视断言。
此外,this answer可能对您的情况有所帮助。