16

Following regex giving me java.lang.IllegalStateException: No match found error

String requestpattern = "^[A-Za-z]+ \\/+(\\w+)";
Pattern p = Pattern.compile(requestpattern);
Matcher matcher = p.matcher(requeststring);
return matcher.group(1);

where request string is

POST //upload/sendData.htm HTTP/1.1

Any help would be appreciated.

3
  • \w (word character) is [A-Za-z0-9_]. It won't match "/", "." or "/" (they all appear after "//"). Commented May 2, 2013 at 17:26
  • I am expecting it to give upload as output Commented May 2, 2013 at 18:33
  • possible duplicate of "No match Found" when using matcher's group method Commented Jun 10, 2014 at 11:57

3 Answers 3

45

No match has been attempted. Call find() before calling group().

public static void main(String[] args) {
    String requeststring = "POST //upload/sendData.htm HTTP/1.1";
    String requestpattern = "^[A-Za-z]+ \\/+(\\w+)";
    Pattern p = Pattern.compile(requestpattern);
    Matcher matcher = p.matcher(requeststring);
    System.out.println(matcher.find());
    System.out.println(matcher.group(1));
}

Output:

true
upload
Sign up to request clarification or add additional context in comments.

Comments

3

The Matcher#group(int) throws :

IllegalStateException - If no match has yet been attempted, or if the 
previous match operation failed.

Comments

0

Your expression requires one or more letters, followed by a space, followed by one or more forward slashes, followed by one or more word characters. Your test string doesn't match. The exception is triggered because you're trying to access a group on a matcher that returns no matches.

Your test string matches up to the slash after "upload", because the slash isn't matched by \w, which only includes word characters. Word characters are letters, digits, and underscores. See: http://www.regular-expressions.info/charclass.html#shorthand

1 Comment

I am expecting it to give upload as output

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.