Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Java regex matcher not working

Tags:

java

regex

Code :

import java.util.regex.*;

public class eq {
    public static void main(String []args) {
        String str1 = "some=String&Here&modelId=324";
        Pattern rex = Pattern.compile(".*modelId=([0-9]+).*");
        Matcher m = rex.matcher(str1);
        System.out.println("id = " + m.group(1));
    }
}

Error :

Exception in thread "main" java.lang.IllegalStateException: No match found

What am I doing wrong here ?

like image 639
vivek Avatar asked Mar 01 '13 08:03

vivek


2 Answers

You need to call find() on the Matcher before you can call group() and related functions that queries about the matched text or manipulate it (start(), end(), appendReplacement(StringBuffer sb, String replacement), etc.).

So in your case:

if (m.find()) {
    System.out.println("id = " + m.group(1));
}

This will find the first match (if any) and extract the first capturing group matched by the regex. Change if to while loop if you want to find all matches in the input string.

like image 161
nhahtdh Avatar answered Sep 22 '22 14:09

nhahtdh


You must add this line before calling group():

m.find();

This moves the pointer to the start of the next match, if any - the method returns true if a match is found.

Usually, this is how you use it:

if (m.find()) {
    // access groups found. 
}
like image 39
Bohemian Avatar answered Sep 20 '22 14:09

Bohemian