Non-capturing group regex not working in Java
Online REGEX testers show non-holding groups are 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
source to share
This assumption is incorrect, as it matcher.group(0)
always returns your full text using the latest methods find
or matches
.
To get 290825814
, you have to 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
}
source to share
From the Documentation for the mapping :
Capture groups are indexed from left to right, starting with one. Group zero denotes the entire pattern, so m.group (0) is equivalent to m.group ().
Since 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 whole template wrapped in a non-capturing group.
source to share