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?
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).Note the
while, which will loop through all matches and tell you group 1 from each.