0

I'm trying to match cases where a sequence of characters contains three or more identical characters in any position, as shown in the following code:

class TRY {
    public static void main(String[] args) {
      String a = "aaaam";
      String b = "aacccccccc";
      String c = "aaffffkb";
      if (b.matches("([a-zA-Z0-9])\\1+"))
          System.out.println("Matches!"); // Display the string.
    }
}

There are many other questions online that suggest using a regular expression like ([a-zA-Z0-9])\\1+ ; "([a-z\\d])\\1{3,}" ; or "([a-z\\d])\\1\\1". The [a-zA-Z0-9] should match any character, and the \\1 should reference the matched character. However none of these match any of my strings, and I don't understand why.

YCF_L
  • 51,266
  • 13
  • 85
  • 129
Alessandro
  • 3,909
  • 11
  • 61
  • 127
  • create pattern and use `find` – Pavneet_Singh Aug 30 '17 at 13:24
  • `".*([a-zA-Z0-9])\\1{2}.*"` – Avinash Raj Aug 30 '17 at 13:24
  • what is the expected output of each input? – YCF_L Aug 30 '17 at 13:25
  • The output should just be a yes or no. I also tried with matcher.matches() and it doesn't work. String.matches() behaves in the same way as Matcher, so I just assumed that the error was in the regex. – Alessandro Aug 30 '17 at 13:30
  • @Wiktor Stribiżew i tried to propose a solution using replaceAll with one of the OP's regex you can check my solution here [ideone](https://ideone.com/J7o2lD) is it a correct one or it is better to use [pattern](https://stackoverflow.com/questions/8923398/regex-doesnt-work-in-string-matches) like the duplicate question? – YCF_L Aug 30 '17 at 13:37
  • @YCF_L No need for work arounds, `Pattern#find()` is the easiest way. – Wiktor Stribiżew Aug 30 '17 at 13:39

0 Answers0