Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Regular Expression throwing error

Tags:

java

regex

perl

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;
like image 394
SexyBeast Avatar asked Apr 22 '26 05:04

SexyBeast


1 Answers

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);
like image 157
Marko Topolnik Avatar answered Apr 24 '26 19:04

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!