user471011
user471011

Reputation: 7374

Java: Regular expression doesn't work as expected

I have the following piece of code:

String range = "(15-42)";
String regexp = "(\\d{1,})(\\d{1,})";

Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(range);

m.find();

System.out.println(m.groupCount());

for(int i=0; i<=m.groupCount(); i++){
System.out.println("value:" + m.group());
}

And then I have the following output:

2
value: 15
value: 1
value: 5

But I'm only expecting to see 2 values: 15 and 42.

Why doesn't this work as expected?

Upvotes: 2

Views: 76

Answers (3)

Lucifer
Lucifer

Reputation: 1

Its a different method but you can use this solution

    System.out.println(m.groupCount());
    String[] value = m.group().split("-");

    for(int i=0; i<value.length; i++){
    System.out.println("value:" + value[i]);
    }

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626835

You need to add hyphen to the regex and use .group(i) and start with index 1 (because m.group(0) is the whole match value that you do not need):

String range = "(15-42)";
String regexp = "(\\d{1,})-(\\d{1,})";
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(range);
if (m.find()) {
    System.out.println(m.groupCount());
    for(int i=1; i<=m.groupCount(); i++){
        System.out.println("value:" + m.group(i));
    }
}

See IDEONE demo

Now, you will have

2               // This is the number of capturing groups
value:15        // This is the value of the first capturing group
value:42        // This is the value of the second capturing group

Upvotes: 1

Tunaki
Tunaki

Reputation: 137084

The mistake is that you are always calling m.group() when you should be calling m.group(i).

The other mistake is that you forgot the hyphen in your regex.

Working code:

String range = "(15-42)";
String regexp = "(\\d{1,})-(\\d{1,})";

Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(range);
m.find();
for (int i = 0; i <= m.groupCount(); i++) {
    System.out.println("value:" + m.group(i));
}

This prints the expected:

value:15-42
value:15
value:42

Upvotes: 1

Related Questions