0

I'm trying to detect if there are any duplicate characters in a string using regex. When I test the pattern and input in an online regex tester, it says find() should be true. But it doesn't work in my program. I'm using info from: regex to match a word with unique (non-repeating) characters.

What's happening? Am I using regex correctly in Java?

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Test {
    public static void main(String[] args) {
        Pattern pat = Pattern.compile("(.).*\1");
        String s = "1112";
        Matcher m = pat.matcher(s);
        if (m.find()) System.out.println("Matches");
        else System.out.println("No Match");
     }
}

Regex tester screenshot

Community
  • 1
  • 1
Alex_B
  • 1,651
  • 4
  • 17
  • 24

1 Answers1

1

The backreference needs to be escaped

Pattern pattern = Pattern.compile("(.).*\\1");
Reimeus
  • 158,255
  • 15
  • 216
  • 276