开发者

how to check if a string contains an alphanum chars appears at least n times consecutively

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,开发者_StackOverflow中文版}


(\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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜