NedStarkOfWinterfell
NedStarkOfWinterfell

Reputation: 5153

Java Regular Expression throwing error

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;

Upvotes: 2

Views: 132

Answers (3)

Marko Topolnik
Marko Topolnik

Reputation: 200168

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);

Upvotes: 8

Ayaz Ali Khatri
Ayaz Ali Khatri

Reputation: 483

Try This:

public static String stripNonDigits(final String input){
  final StringBuilder sb = new StringBuilder();
  for(int i = 0; i < input.length(); i++){
    final char c = input.charAt(i);
    if(c > 47 && c < 58){
        sb.append(c);
    }
}
return sb.toString();

} Test Code:

public static void main(final String[] args){
final String input = "0-123-abc-456-xyz-789";
final String result = stripNonDigits(input);
System.out.println(result);
 }

Output:

0123456789

Might be helpfull thanks

Upvotes: 1

PermGenError
PermGenError

Reputation: 46418

you have to invoke Matcher.find() before calling Matcher.group()

String text = "Kane is 12345 feet high";
Pattern p = Pattern.compile("Kane is (\\d+) feet high");
Matcher m = p.matcher(text);
if(m.find()){
String s0 = m.group(0);

}

Suppose the text is Kane is 12345 feet high. I want to capture 12345

i think, your Regex should be like below in order to just capture the number in your text.

    Pattern p = Pattern.compile("\\d+");

Upvotes: 6

Related Questions