0

Java Code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegExpTest {
    public static void main(String[] args) {

        String str = "X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001";
        String p = "Value = (.*?), ";
        Pattern pattern = Pattern.compile(p);
        Matcher matcher = pattern.matcher(str);
        if (matcher.find()){
             System.out.println(matcher.group(1));
             System.out.println(matcher.group(2));
             System.out.println(matcher.group(3));
        }
    }
}

Java code's output:

$ java RegExpTest 
-0.525108
Exception in thread "main" java.lang.IndexOutOfBoundsException: No group 2
        at java.util.regex.Matcher.group(Matcher.java:487)
        at RegExpTest.main(RegExpTest.java:15)
$ 

Python code (in Interpreter):

>>> import re
>>> re.findall("Value = (.*?), ", 'X-Value = -0.525108, Y-Value = 7.746691, Z-Value = 5.863008, Timestamp(milliseconds) = 23001;')
['-0.525108', '7.746691', '5.863008']
>>> 

So, why is Java unable to match all the occurrences of the match?

3 Answers 3

7

It's because a group for a java match is a capturing bracket.

Your regex only has one set of non-escaped (ie capturing) brackets, the (.*?).

Group 1 contains the value that gets matched.

There is no group 2 because there is no second set of brackets in your regex.

In the java example, you want to loop through all matches, and print matcher.group(1).

while ( matcher.find() ) {
    System.out.println(matcher.group(1));
}

Note the while, which will loop through all matches and tell you group 1 from each.

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

Comments

2

Java's java.util.regex.Matcher.find attempts to find the next value that matches, not all the values that match. Change if to while and you should get the result you are looking for.

...
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
    System.out.println(matcher.group(1));
...

Comments

0

Because you're using it wrong.

matcher.group() returns the values of the various capturing groups within a single match. You only have one capturing group (i.e. one set of parentheses in your pattern).

matcher.find() is the method that returns the next match, if you call it repeatedly. Usually in a while loop, e.g.:

    while (matcher.find()){
         System.out.println(matcher.group(1));
    }

See more here.

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.