As it has been stated, please do not use regular to process XML. Below is the approach you should take (code adapted from here and here).:
String str = "<customer>\n" +
" <name>Customer name</name>\n" +
" <address>\n" +
" <postalcode>94510</postalcode>\n" +
" <town>Green Bay</town>\n" +
" </address>\n" +
" <phone>0645878787</phone>\n" +
"</customer>";
ByteArrayInputStream bais = new ByteArrayInputStream(str.getBytes());
DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(bais);
//optional, but recommended
//read this - http://stackoverflow.com/questions/13786607/normalization-in-dom-parsing-with-java-how-does-it-work
doc.getDocumentElement().normalize();
System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
NodeList nList = doc.getElementsByTagName("address");
for(int i = 0; i < nList.getLength(); i++)
{
NodeList children = nList.item(i).getChildNodes();
for(int j = 0; j < children.getLength(); j++)
{
Node current = children.item(j);
if((current.getNodeName().equals("postalcode")) && (current.getTextContent().equals("94510")))
{
current.getParentNode().getParentNode().removeChild(nList.item(i));
}
}
}
Transformer transformer = TransformerFactory.newInstance().newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
StreamResult result = new StreamResult(new StringWriter());
DOMSource source = new DOMSource(doc);
transformer.transform(source, result);
String xmlString = result.getWriter().toString();
System.out.println(xmlString);
Which yields:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<customer>
<name>Customer name</name>
<phone>0645878787</phone>
</customer>
If you really, really must use regular expressions, take a look at the below:
String str = "<customer>\n" +
" <name>Customer name</name>\n" +
" <address>\n" +
" <postalcode>94510</postalcode>\n" +
" <town>Green Bay</town>\n" +
" </address>\n" +
" <phone>0645878787</phone>\n" +
"</customer>";
System.out.println(str.replaceAll("(?s)<address>.+?<postalcode>94510</postalcode>.+?</address>.+?<phone>", "<phone>"));
Yields:
<customer>
<name>Customer name</name>
<phone>0645878787</phone>
</customer>