0

我正在做一个模式匹配 matcher.matches 是假的,而 matcher.replaceAll 实际上找到了模式并替换它。matcher.group(1) 也返回异常。

@Test
public void testname() throws Exception {
    Pattern p = Pattern.compile("<DOCUMENT>(.*)</DOCUMENT>");
    Matcher m = p.matcher("<RESPONSE><DOCUMENT>SDFS878SDF87DSF</DOCUMENT></RESPONSE>");
    System.out.println("Why is this false=" + m.matches());
    String s = m.replaceAll("HEY");
    System.out.println("But replaceAll found it="+s);

}

我需要 matcher.matches() 返回 true,并且 matcher.group(1) 返回 "<DOCUMENT>SDFS878SDF87DSF</DOCUMENT>"

在此先感谢您的帮助。

4

1 回答 1

2
final Pattern pattern = Pattern.compile("<DOCUMENT>(.+?)</DOCUMENT>");
final Matcher matcher = pattern.matcher("<RESPONSE><DOCUMENT>SDFS878SDF87DSF</DOCUMENT></RESPONSE>");
if (matcher.find())
{
    System.out.println(matcher.group(1));
    // code to replace and inject new value between the <DOCUMENT> tags
}
于 2013-04-06T16:40:29.303 回答