3

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

Community
  • 1
  • 1
Ben Arnao
  • 153
  • 4
  • 14
  • 1
    It prints the entire string because you're telling it to. `m.group()` refers to the entire match. If you're only interested in a portion of the matched text, use a capture group, e.g. `Game No : ([0-9]*)` and then `print(m.group(1))`. – Aran-Fey Feb 28 '17 at 17:32
  • Just because `Game No` is in a non-capturing group, doesn't mean that it isn't part of the match. You want a lookbehind if you want to exclude it from the match. – Gerrit0 Feb 28 '17 at 17:33
  • What makes you think that it should print only numbers? – Pshemo Feb 28 '17 at 17:33
  • Your regex won't match your string `"Game No : 432543254 \n"`, there is no provision for a space between the last number and the newline. Also, the non-capture grouping `(?:Game No : )` is not necessary, why are you using it? –  Feb 28 '17 at 18:10

1 Answers1

3

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.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563