简体   繁体   中英

regular expression to match 4 or more identical characters

I need regular expressions to match the below case.

4 or more consecutive identical characters/numbers; eg 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.

  1. Please let me know what change i need to make it match 4 or more identical characters.

  2. 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 "\\\\" ?

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.

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM