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.

1 Answer 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
}
Sign up to request clarification or add additional context in comments.

3 Comments

I could have something like this for the xml "<RESPONSE><FILE>...</FILE><DOCUMENT>SDFS878SDF87DSF</DOCUMENT><RATE>...</RATE></RESPONSE>" I need to extract and replace the DOCUMENT section.
Then your question is worded wrong if you want to extract the text between the <DOCUMENT> tags. I'll update my answer.
Some more info on matches() vs find() here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.