Regex matching repeating digits (3 or more) ignore whitespace

937 views Asked by At

I have been investigating although I have not yet managed to figure out how to create a regex that will match digits only which repeat successively 3 or more times while ignoring whitespaces.

For example I have currently (\d)\1{3,} which matches

11112568856 etc 1111 2568 856 etc

although it fails when the repetition exists before and after a space

6111 1256 8856

What do I need to add to the regex in order to match this?

3

There are 3 answers

0
RomanPerekhrest On BEST ANSWER

Use backreferences to match the same digit again:

(\s?\d\s?)(\s?\1){2,}

https://regex101.com/r/FNNS1z/3

http://www.regular-expressions.info/backref.html

0
S.C On

This works I think:

(\d)\s?(\1\s?){3,}

The "\s?" part accounts for optional whitespaces, "?" is equal to {0,1}.

I checked in R with stringr package (note that I had to escape the backslashes):

> str_extract_all("221 1 1 122 ", "(\\d)\\s?(\\1\\s?){3,}")
[[1]]
[1] "1 1 1 1"
0
Graham On

None of the answers worked for me (in PHP), but this seems to do the job:

(\\d(\\s*)?){3,}