Java Regular Expression找不到匹配项

时间:2014-10-27 19:32:52

标签: java regex

我正在使用Java正则表达式问题。我需要匹配的字符串遵循以下模式:378-Columbian Forecast Yr-NB-Q-Columbian_NB我需要提取第一个和第二个-之间的内容。

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)进行测试时,结果是找不到匹配。

1 个答案:

答案 0 :(得分:5)

您需要首先使正则表达式引擎找到匹配。通常让我们迭代我们使用的所有匹配部分

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
}

顺便说一句,如果你想找到至少15个东西,那么你想要找到它至少16次,所以你的正则表达式似乎可以重写为

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