Java RegEx找不到匹配错误

时间:2013-05-02 17:23:44

标签: java regex

正则表达式给我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

任何帮助都将不胜感激。

3 个答案:

答案 0 :(得分:27)

未尝试匹配。在致电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

答案 1 :(得分:2)

Matcher#group(int)投掷:

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

答案 2 :(得分:0)

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

“上传”后,您的测试字符串与斜杠匹配,因为斜杠与\w不匹配,{{1}}仅包含单词字符。单词字符是字母,数字和下划线。请参阅:http://www.regular-expressions.info/charclass.html#shorthand