I am testing for a string if it contains at least n chars in consecutive order:
I have this regex but it doesn't seems to work
(\w\1){3,}
Can someone please help!!!
Thanks
I am testing for a string if it contains at least n chars in consecutive order:
I have this regex but it doesn't seems to work
(\w\1){3,}
Can someone please help!!!
Thanks
(\w)\1{3,}
This makes sure that you have a character repeating at least four times.
The problem with (\w\1)
is that the backreference \1
is inside the capturing group itself. \1
refers to the character(s) matched by the first parenthetical ()
group.
If you want to capture the whole matched string, enclose the regex in another parenthetical group.
((\w)\2{3,})
Note that here the index of backreference is \2
as \1
refers to the outer parentheses.
Check the example:
Regex : ((\w)\2{3,})
TestString : bbaaaaaacc
Match : aaaaaa
$1 : aaaaaa
$2 : a
Are you looking for n of the same character or just n characters?
(\w)\1{2,}
finds one character and then two more of the same. So it will match if you have 3 or more of the same char consecutive order in the string.
(\w){3,}
will match 3 or more characters.