Java Regular Expression找不到匹配项

时间:2022-06-11 21:44:54

I am having Java regex issues. The string I need matching follows this pattern: 378-Columbian Forecast Yr-NB-Q-Columbian_NB I need to extract what is between the first and second -.

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

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

Here is my reasoning behind this regex [^-]{15,}[^-]:

这是我的正则表达式[^ - ] {15,} [^ - ]背后的推理:

I only want what is between the hyphens so I used [^-]. There are multiple instances of text between hyphens so I picked a number that was large enough it won't pick up on the smaller matches. So I used {15,}

我只想要连字符之间的东西,所以我用[^ - ]。连字符之间有多个文本实例,所以我选择了一个足够大的数字,它不会在较小的匹配上获取。所以我使用{15,}

My error:

 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)

When I tested my regex pattern against the string here: http://regexpal.com/ the pattern matched. When I tested using this tester more specifically for Java (http://www.regexplanet.com/advanced/java/index.html) The results were the match wasn't found.

当我在这里测试我的正则表达式模式时:http://regexpal.com/模式匹配。当我使用此测试仪更具体地针对Java进行测试时(http://www.regexplanet.com/advanced/java/index.html)结果是未找到匹配项。

1 个解决方案

#1


You need to make regex engine find its match first. Generally to let us iterate over all matching parts we use

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

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}

BTW if you want to find at least 15 of something and once more then you want to find it at least 16 times, so it seems that your regex can be rewritten as

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

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

#1


You need to make regex engine find its match first. Generally to let us iterate over all matching parts we use

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

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}

BTW if you want to find at least 15 of something and once more then you want to find it at least 16 times, so it seems that your regex can be rewritten as

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

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