Alex_B Alex_B - 2 months ago 11
Java Question

Regex find() not true; detect duplicate characters in string

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

Answer

The backreference needs to be escaped

Pattern pat = Pattern.compile("(.).*\\1");
Comments