regex - 正则表达式查找长度为 n 的重复数
问题描述
我正在尝试使用 golang 正则表达式来查找数字的重复。这是我试图找到长度为 8 的重复数字的内容。我试图按照Regex 的建议来查找重复数字
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")
}
}
注意:例如,您的复杂正则表达式将捕获 8 位以上的单词,因此我对其进行了一些更正。
来自官方 GitHub,正如评论中提到的:
RE2 不支持仅已知存在回溯解决方案的构造。因此,不支持反向引用 和环视断言。
此外,此答案可能对您的情况有所帮助。
推荐阅读
- azure - 带有 AzureADB2C 的 SaaS 应用程序:客户端 SSO 的用户流?
- sails.js - How to fix error caused by userconfig probably by sails?
- bash - How can I invoke both BASH and CSH shells in a same script
- php - 使用php从MySQL中选择并打印数据,不起作用
- c# - 具有 2 个时间数据的 LinkedList
- html - CSS文件未在浏览器中更新
- android - Android资产,我如何从子文件夹中读取文件?
- amazon-web-services - 我应该做很多较小的请求,还是使用 s3 做更少但更大的请求来传递数据
- python-3.x - 在 xlib 上使用 ctypes 时出现分段错误
- node.js - 如何将 node.js express 服务器转换为 AWS lambda?