Reputation: 521
I need regular expressions to match the below case.
4 or more consecutive identical characters/numbers; e.g. 1111, aaaa, bbbb, 2222, etc.
I tried this pattern matching
Pattern pattern = Pattern.compile("([a-z\\d])\\1\\1", Pattern.CASE_INSENSITIVE);
But i found that it matches only 3 or more identical characters.
Please let me know what change i need to make it match 4 or more identical characters.
Also i need to check for special character "\" . Please tell me how i need to add in the pattern matching statement ...do i need to give as "\\" ?
Upvotes: 2
Views: 1860
Reputation: 10605
You might be able to use {3,} as well...
"([a-z\\d])\\1{3,}"
instead of adding \\1 multiple times (haven't tried this in java).
Upvotes: 2
Reputation: 16711
You need to add another backreference:
Pattern pattern = Pattern.compile("([a-z\\d])\\1\\1\\1", Pattern.CASE_INSENSITIVE);
Basically, the parenthesis indicate a matched group. From there the three backslashed ones, refer to this matched group, meaning that all four groups must be the same.
Upvotes: 1