Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java RegEx no match found error

Tags:

java

regex

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.

like image 458
Ananda Avatar asked May 02 '13 17:05

Ananda


2 Answers

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
like image 144
acdcjunior Avatar answered Sep 28 '22 01:09

acdcjunior


The Matcher#group(int) throws :

IllegalStateException - If no match has yet been attempted, or if the 
previous match operation failed.
like image 26
AllTooSir Avatar answered Sep 28 '22 02:09

AllTooSir