Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Non-Capturing group regex not working in Java

Tags:

java

regex

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
like image 789
Neil Avatar asked Dec 14 '22 19:12

Neil


2 Answers

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
}
like image 139
anubhava Avatar answered Jan 02 '23 22:01

anubhava


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.

like image 40
Strikeskids Avatar answered Jan 02 '23 22:01

Strikeskids