I am trying to capture a certain number chunk from within a text. Suppose the text is Kane is 12345 feet high. I want to capture 12345. I am trying to use this:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
String text = "Kane is 12345 feet high";
Pattern p = Pattern.compile("Kane is (\\d+) feet high");
Matcher m = p.matcher(text);
String s0 = m.group(0);
However I am getting a Match not found error. What am I doing wrong here? I mean, in Perl, this perfectly prints out 12345:
$foo = "Kane is 12345 feet high";
$foo =~ /Kane is (\d+) feet high/;
print $1;
Just instantiating Matcher isn't enough: you must call m.matches() and the standard practice would be to put it in an if:
if (m.matches()) s0 = m.group(1);
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