Ben Arnao
Ben Arnao

Reputation: 165

Non capturing group java regex

I saw this post What is a non-capturing group? What does a question mark followed by a colon (?:) mean?

And i figured that the following would work, but it doesn't...

I have a String "Game No : 432543254 \n"

Pattern p = Pattern.compile("(?:Game No : )[0-9]*?(\n)");
Matcher m = p.matcher(curr);
m.find();
System.out.print(m.group());

But the code above prints the entire string, not just the numbers i want

Upvotes: 3

Views: 2921

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

A non-capturing group does not capture, but still matches the string. Besides, there is a space between the digits and the newline in your pattern, so it won't match.

To get the digits, you would use a capturing group around the digit matching pattern, like this:

Pattern p = Pattern.compile("Game No : ([0-9]+)");
Matcher m = p.matcher(curr);
if (m.find()) {
    System.out.print(m.group(1));
}

See the Java demo

Or, use a non-regex solution, just split with : and get the second item of the resulting array and trim it.

Upvotes: 3

Related Questions