The online REGEX testers shows the non-captuting groups are getting ignored but from java code it is not ignored.
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
class Ideone
{
public static void main (String[] args) throws java.lang.Exception
{
Pattern PATTERN = Pattern.compile("(?:execute: ID: \\[\\s)([0-9]*)(?:\\s\\])");
Matcher matcher = PATTERN.matcher("controllers.pring execute: ID: [ 290825814 ] executing bean: [ strong ]");
if (matcher.find()) {
System.out.println(matcher.group(0));
}
}
}
Output
execute: ID: [ 290825814 ]
Expected
290825814
That is wrong assumption as matcher.group(0)
always returns you full matched text by your latest find
or matches
methods.
To get 290825814
you must use:
Pattern PATTERN = Pattern.compile("(?:execute: ID: \\[\\s)([0-9]*)(?:\\s\\])");
Matcher matcher = PATTERN.matcher("controllers.pring execute: ID: [ 290825814 ] executing bean: [ strong ]");
if (matcher.find()) {
System.out.println(matcher.group(1)); // 290825814
}
From the Matcher documentation:
Capturing groups are indexed from left to right, starting at one. Group zero denotes the entire pattern, so the expression m.group(0) is equivalent to m.group().
Because you are using group 0, you are capturing the entire pattern, coincidentally the same as your non-capturing group. I'm not sure why you have the entire pattern wrapped in a non-capturing group.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With