DEV Community

Ethan
Ethan

Posted on • Updated on

Repeated Capturing Group

Regular expression can be used to check a string or a pattern is repeated in a string. For example, if you want to check if the string 'abc' is repeated for exactly 3 times in a string, you can use the following regex: (abc)\1{2}, or it would be like this in Java after adding the escape characters:

Pattern.compile("(abc)\\1{2}");
Enter fullscreen mode Exit fullscreen mode

The \1 in the regex matches the first capturing group in the regex. If you want it to match the second capturing group, you can use \2 and so on.

It is also possible check if a capturing group is repeated at least n times or more than n times. For examples,

  • to check if abc is repeated in a string for at least 5 times, (abc)\1{4,}
  • to check if abc is repeated in a string for less than 5 times, (abc)\1{0,4}

Top comments (0)