15

按照正则表达式给我java.lang.IllegalStateException: No match found错误

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

请求字符串在哪里

POST //upload/sendData.htm HTTP/1.1

任何帮助,将不胜感激。

4

3 回答 3

38

没有尝试匹配。打电话find()前打电话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));
}

输出:

true
upload
于 2013-05-02T18:40:06.100 回答
3

Matcher#group ( int)抛出:

IllegalStateException - If no match has yet been attempted, or if the 
previous match operation failed.
于 2013-05-02T17:26:43.807 回答
0

您的表达式需要一个或多个字母,后跟一个空格,后跟一个或多个正斜杠,后跟一个或多个单词字符。您的测试字符串不匹配。触发异常是因为您尝试访问不返回匹配项的匹配器上的组。

您的测试字符串与“上传”后的斜线匹配,因为斜线与 不匹配\w,它只包含单词字符。单词字符是字母、数字和下划线。见:http ://www.regular-expressions.info/charclass.html#shorthand

于 2013-05-02T17:26:29.320 回答