Java 正则表达式未找到匹配项错误

2022-09-03 09:03:01

遵循正则表达式给我错误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

任何帮助将不胜感激。


答案 1

未尝试匹配项。呼叫后再呼叫 。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

答案 2

Matcher#group(int) 投掷 :

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