首页 > 解决方案 > 正则表达式查找长度为 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")
  }

输出:匹配

有什么建议么

标签: regexgo

解决方案


如果您需要在字符串的开头准确地捕获八次相同数字的重复作为单个单词,那么这将起作用:

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 不支持仅已知存在回溯解决方案的构造。因此,不支持反向引用环视断言。

此外,此答案可能对您的情况有所帮助。


推荐阅读