Regular Expression to match 3 or more Consecutive Sequential Characters and Consecutive Identical Characters

sandy0093 picture sandy0093 · Jan 16, 2012 · Viewed 86.1k times · Source

I need regular expressions to match the below cases.

  1. 3 or more consecutive sequential characters/numbers; e.g. 123, abc, 789, pqr, etc.
  2. 3 or more consecutive identical characters/numbers; e.g. 111, aaa, bbb, 222, etc.

Answer

Milad Naseri picture Milad Naseri · Jan 16, 2012

I don't think you can use regex for the first case. The second case is easy though:

Pattern pattern = Pattern.compile("([a-z\\d])\\1\\1", Pattern.CASE_INSENSITIVE);

Since \\1 represents part matched by group 1 this will match any sequence of three identical characters that are either within the range a-z or are digits (\d).