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

1 Answer 1

1

The backreference needs to be escaped

Pattern pattern = Pattern.compile("(.).*\\1");
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.