I'm always struggling with Regex, I want to replace multiple tags in my xml by one.
The content of each tag of <b>
is dynamic, and it could include another tags
So having
<a>
<c>hi</c>
<b>hello1</b>
<b><f>bla</f></b>
<b>hello3</b>
<b>hello4</b>
</a>
I want to replace all <b>
tags by just one tag of mine <b>world</b>
and left <c>
as it is.
<a>
<c>hi</c>
<b>world</b>
</a>
Any idea how? It's better use an XML Parser instead?
Regards.
CodePudding user response:
XSLT solution:
<xsl:template match="/a">
<a>
<xsl:copy-of select="c"/>
<b>world</b>
</a>
</xsl:template>
CodePudding user response:
Try this
String html = " <a>"
"<c>hi</c>"
"<b>hello1</b>"
"<b>hello2</b>"
"<b>hello3</b>"
"<b>hello4</b>"
"</a>";
html = html.replaceAll("\\s", "").replaceAll("<b>.*</b>", " ").replaceFirst(" ", "<b>world</b>");
This is the output
<a><c>hi</c><b>world</b></a>
CodePudding user response:
Use <a>.*<\/a>
pattern with dot all option (flag s) and replace by something like <a><b>world</b></a>
or replace <b>.*<\/b>
by <b>world</b>