0

I am doing a Pattern match the matcher.matches is coming as false, while the matcher.replaceAll actually finds the pattern and replaces it. Also the matcher.group(1) is returning an exception.

@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);

}

I need the matcher.matches() to return true, and the matcher.group(1) to return "<DOCUMENT>SDFS878SDF87DSF</DOCUMENT>"

Thanks in advance for the help.

saad
  • 371
  • 3
  • 13

1 Answers1

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
}
syb0rg
  • 8,057
  • 9
  • 41
  • 81
  • I could have something like this for the xml "...SDFS878SDF87DSF..." I need to extract and replace the DOCUMENT section. – saad Apr 06 '13 at 16:51
  • Then your question is worded wrong if you want to extract the text between the `` tags. I'll update my answer. – syb0rg Apr 06 '13 at 16:54
  • Some more info on matches() vs find() [here](http://stackoverflow.com/questions/4450045/difference-between-matches-and-find-in-java-regex) – Jake Walsh Jul 10 '13 at 17:38