Regex detects any duplicate character, but with an optional space in between
So, I currently have the following regex pattern allowing me to detect any string containing 9 characters that are the same in sequence.
/^.*(\S)\1{9,}.*$/
This works fine with a line like the following: this a tesssssssssst
however, I want it to also detect a line like this: this a tess sss ssssst
(Same amount of repeated character, but with optional space)
Any ideas?
source to share
You need to put the backreference in a group and add an optional space to the group:
^.*(\S)(?: ?\1){9,}.*$
See regex demo . If there can be more than 1 space between them, replace ?
with *
.
The part .*$
is only needed if you need to match the entire string, for methods that allow partial matches you can use ^.*(\S)(?: ?\1){9,}
.
If there is a space, replace the space with \s
in the pattern.
source to share
You can check for more than one character this way.
It is limited only by the number of available capture groups.
This checks for 1 to 3 characters.
(\S)[ ]*(\S)?[ ]*(\S)?(?:[ ]*(?:\1[ ]*\2[ ]*\3)){9,}
# 1-3 Characters
( \S ) # (1)
[ ]*
( \S )? # (2)
[ ]*
( \S )? # (3)
# Add more here
(?:
[ ]*
(?: \1 [ ]* \2 [ ]* \3 )
# Add more here
){9,}
source to share