1

Im trying to find whether a word contains consecutive identical strings or not, using java.regex.patterns, while testing an regex with matcher, It returns true. But if I only use like this : System.out.println("test:" + scanner.hasNext(Pattern.compile("(a-z)\\1"))); it returns false.

public static void test2() {
String[] strings = { "Dauresselam", "slab", "fuss", "boolean", "clap", "tellme" };

String regex = "([a-z])\\1";
Pattern pattern = Pattern.compile(regex);
for (String string : strings) {
    Matcher matcher = pattern.matcher(string);
    if (matcher.find()) {
        System.out.println(string);
    }
}
}

this returns true. which one is correct.

2 Answers 2

2

The pattern ([a-z])\\1 uses a capturing group to match a single lowercase character which is then followed by a backreference to what is captured in group 1.

Ih you have Dauresselam for example, it would match the first s in the capturing group and then matches the second s. So if you want to match consecutive characters you could use that pattern.

The pattern (a-z)\\1 uses a capturing group to match a-z literally and then then uses a backreference to what is captured in group 1. So that would match a-za-z

Sign up to request clarification or add additional context in comments.

Comments

0

It depends on what you want. Here you use parenthesis:

Pattern.compile("(a-z)\\1").

Here you use Square brackets inside pareanthesis:

String regex = "([a-z])\\1";

To compare, you should obviously use the same pattern.

1 Comment

thank you.. could you tell me the difference between compile and matcher

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.