2013-05-02 26 views
6

以下的正則表達式給我java.lang.IllegalStateException: No match found錯誤Java的正則表達式不匹配發現錯誤

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 

任何幫助,將不勝感激。

+0

'\ w'(字符)被'[A-ZA-Z0-9_]'。它不會匹配「'/'','''''」或「'/'」(它們全都出現在「''''」之後)。 – acdcjunior 2013-05-02 17:26:54

+0

我期待它給上傳作爲輸出 – Ananda 2013-05-02 18:33:47

+0

[「使用匹配器組方法時找不到匹配項」的可能重複](http://stackoverflow.com/questions/5674268/no-match-found-when-using-matchers -group-method) – anotherdave 2014-06-10 11:57:02

回答

24

不匹配已嘗試。在致電group()之前致電find()

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 
0

您的表情需要一個或多個字母,後跟一個空格,後跟一個或多個正斜槓,後跟一個或多個單詞字符。你的測試字符串不匹配。由於您試圖訪問匹配器上不返回匹配的組,因此會觸發異常。

由於斜槓與\w(僅包含單詞字符)不匹配,因此您的測試字符串與「上載」後的斜槓匹配。單詞字符是字母,數字和下劃線。請參閱:http://www.regular-expressions.info/charclass.html#shorthand

+0

我期待它能夠提供上傳作爲輸出 – Ananda 2013-05-02 18:32:42

2

Matcher#group(int)拋出:

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