Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple java regex throwing illegalstateexception [duplicate]

Im trying to do a quick sanity check... and its failing. Here is my code -

import java.util.regex.*;

public class Tester {
    public static void main(String[] args) {
        String s = "a";
        Pattern p = Pattern.compile("^(a)$");
        Matcher m = p.matcher(s);
        System.out.println("group 1: " +m.group(1));
    } 
}

And what I would expect is to see group 1: a. But instead I get an IllegalStateException: no match found and I have no idea why.

Edit: I also tries printing out groupCount() and it says there is 1.

like image 807
David says Reinstate Monica Avatar asked Aug 15 '13 16:08

David says Reinstate Monica


1 Answers

You need to invoke m.find() or m.matches() first to be able to use m.group.

  • find can be used to find each substring that matches your pattern (used mainly in situations where there is more than one match)
  • matches will check if entire string matches your pattern so you wont even need to add ^ and $ in your pattern.

We can also use m.lookingAt() but for now lets skip its description (you can read it in documentation).

like image 102
Pshemo Avatar answered Sep 30 '22 08:09

Pshemo