【问题标题】:Java Regular Expression doesn't find a matchJava 正则表达式找不到匹配项
【发布时间】:2014-10-27 19:32:51
【问题描述】:

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

【问题讨论】:

    标签: java regex


    【解决方案1】:

    你需要先让正则表达式引擎find匹配。通常让我们遍历我们使用的所有匹配部分

    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,}");
    //                                         ^^
    

    【讨论】:

      猜你喜欢
      • 2018-07-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      • 2017-10-11
      • 2015-11-13
      • 1970-01-01
      • 2015-06-03
      相关资源
      最近更新 更多