Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex detect any repeated character but with optional whitespace between

So currently I've got the following regex pattern, allowing me to detect any string containing 9 characters that are the same consecutively.

/^.*(\S)\1{9,}.*$/

This works perfectly with a string like the following: this a tesssssssssst however I wish for it to also detect a string like this: this a tess sss ssssst (Same number of the repeated character, but with optional whitespace)

Any ideas?

like image 328
Matt Cowley Avatar asked Sep 13 '25 23:09

Matt Cowley


1 Answers

You need to put the backreference into a group and add an optional space into the group:

^.*(\S)(?: ?\1){9,}.*$

See the regex demo. If there can be more than 1 space in between, replace ? with *.

The .*$ part is only needed if you need to get the whole line match, for methods that allow partial matches, you may use ^.*(\S)(?: ?\1){9,}.

If any whitespace is meant, replace the space with \s in the pattern.

like image 115
Wiktor Stribiżew Avatar answered Sep 15 '25 13:09

Wiktor Stribiżew