0

I am trying to use golang regexp to find the repetition of digits. Here is what I have tried to find repetitive digits of length 8. I was trying to follow the suggestion at 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")
    }

It always gives me result as "No match". Another way that works it is cumbersome

  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")
  }

Output: Match

Any suggestions

user27111987
  • 995
  • 2
  • 10
  • 26
  • 1
    If you want to match exactly 8 repeating digits, you could use `{7}` instead of `{8}` because the first digit is already matched in the capturing group. Try `^(\d)\\1{7}$` – The fourth bird Apr 14 '19 at 09:24
  • It still says no match – user27111987 Apr 14 '19 at 09:28
  • 2
    [Backreferences are not supported in RE2](https://golang.org/s/re2syntax). – Peter Apr 14 '19 at 09:41
  • regexp not support back reference because of performance, if do wanna use regex, try [pcre](https://godoc.org/?q=pcre). but i think it's also not hard to write some go code. – zzn Apr 14 '19 at 11:11

1 Answers1

1

If you need to catch exactly eight repetitions of the same digit as a single word in the beginning of the string, then this shall work:

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")
    }
}

Note: Your cubersome regexp will catch 8+ digits words, for instance, so I've corrected it a bit.

From official GitHub and as was mentioned in the comments:

RE2 does not support constructs for which only backtracking solutions are known to exist. Thus, backreferences and look-around assertions are not supported.

Also, this answer may be helpful in your situation.

Denis Rasulev
  • 3,744
  • 4
  • 33
  • 47