Gayathri Ganesan
Gayathri Ganesan

Reputation: 53

java regex pattern.compile Vs matcher

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.

Upvotes: 1

Views: 376

Answers (2)

The fourth bird
The fourth bird

Reputation: 163207

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

Upvotes: 2

Poul Bak
Poul Bak

Reputation: 10929

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.

Upvotes: 0

Related Questions