1

at Rubular i was testing my Regular expression:

(\d+).html

Test string:

"/magnoliaAuthor/Services/services/07.html"

Just as I needed, I returned "07" as the first match group. Perfect. I need this regex in an Java environment, so I wrote this piece of code:

import java.util.regex.*;

class Main
{
  public static void main (String[] args) 
  {
    String jcrPath = "/magnoliaAuthor/Services/services/07.html";
    Pattern pattern = Pattern.compile("(\\d+).html");
    Matcher matcher = pattern.matcher(jcrPath);
    System.out.println(matcher.group());
  }
}

As explained here, I added anothere \ to my regex. Sadly for me, when compiling and running the code, I get the following exception: java.lang.IllegalStateException: No match found

Does anybody know why there aren't any matches?

4

2 回答 2

2

javadocMatcher#group()说:

返回与前一个匹配项匹配的输入子序列。

这意味着您必须在使用该方法之前执行matcher.matches()or 。在您的情况下将是正确的,因为检查整个输入字符串是否与模式匹配。matcher.find()group()matcher.find()matcher.matches()

于 2013-05-14T13:18:25.720 回答
2

您还需要应用该模式:

Pattern pattern = Pattern.compile("(\\d+)\\.html"); // compiles the regex
Matcher matcher = pattern.matcher(jcrPath);         // creates a Matcher object 
if (matcher.find()) {                               // performs the actual match
    System.out.println(matcher.group());
}
于 2013-05-14T13:16:22.750 回答