2014-10-27 37 views
0

我有Java正則表達式問題。我需要匹配的字符串遵循以下模式:378-Columbian Forecast Yr-NB-Q-Columbian_NB我需要提取第一個和第二個之間的內容-Java正則表達式找不到匹配項

Pattern modelRegEx = Pattern.compile("[^-]{15,}[^-]"); 
Matcher m = modelRegEx.matcher(temp); 
String model = m.group(0); 

這是我這個表達式[^-]{15,}[^-]背後的原因:

我只是想什麼連字符之間,所以我用[^-]。連字符之間有多個文本實例,所以我選擇了一個足夠大的數字,它不會在較小的匹配中找到。所以我用{15,}

我的錯誤:

Exception in thread "main" java.lang.IllegalStateException: No match found 
at java.util.regex.Matcher.group(Matcher.java:496) 
at alfaSpecificEditCheck.tabTest.main(tabTest.java:21) 

當我測試對這裏的字符串我的正則表達式:http://regexpal.com/匹配的模式。當我測試使用這個測試程序更具體的Java(http://www.regexplanet.com/advanced/java/index.html)結果是匹配沒有被發現。

回答

5

你需要讓正則表達式引擎找到它的匹配首先。一般來說,讓我們遍歷順便說一句,如果你想找到的東西至少15次以上,那麼你想找到它至少16倍,我們使用

Pattern modelRegEx = Pattern.compile("[^-]{15,}[^-]"); 
Matcher m = modelRegEx.matcher(temp); 
while(m.find()){// <-- add this 
    String model = m.group(0); 
    //do stuff with each match you will find 
} 

所有匹配的零件,如此看來,你的正則表達式可以被改寫爲

Pattern modelRegEx = Pattern.compile("[^-]{16,}"); 
//           ^^ 
+0

* facepalm *當然!謝謝! – staples 2014-10-27 19:37:32