Using a regular expression to search for arbitrary lengths of consecutive blocks

I have a string containing ones and zeros. I want to determine if there are substrings of 1 or more characters that are repeated at least 3 times in a row. For example, the string '000' has a substring of length 1 consisting of one null character that is repeated 3 times. The string '010010010011' actually has 3 such substrings, each of which is repeated 3 times ('010', '001' and '100').

Is there a regular expression expression that can find these repeating patterns without knowing either the particular pattern or the length of the pattern? I don't care what the pattern is and what its length is, just that the string contains a 3-peat pattern.

+4
source share
3 answers
(.+)\1\1 

\ may be a different character depending on your choice of language. This means that you need to match any string, and then try to match it again.

\1 means repeat the first match.

+2
source

Something may work here, however, it will tell you if there is a pattern repeated three times, and (I don't think) cannot be expanded to let you know if there are others:

  /(.+).*?\1.*?\1/ 

Violation of this:

  (.+) matches any 1 or more characters, starting anywhere in the string .*? allows any length of interposing other characters (0 or more) \1 matches whatever was captured by the (...+) parentheses .*? 0 or more of anything \1 the original pattern, again 

If you want the repetitions to appear immediately next to them, use

  /(.+)\1\1/ 

... as suggested by @Buh Buh - notation \1 vs. $1 may vary depending on your regexp system.

+3
source

It looks weird, but it could be a solution:

 /000000000|100100100|010010010|001001001|110110110|011011011|101101101|111111111/ 

It contains all possible combinations three times. So your regex will match these numbers (i.e.):

  • 10010010011
  • 00010010011
  • 10110110110

But not for them:

  • 101010101010
  • 001110111110
  • 111000111000

And it doesn't matter where the sequence appears in the entire line.

0
source

Source: https://habr.com/ru/post/1388337/


All Articles