Reputation: 1651
I have the following XML String:
String XML = "<TEST><MESSAGEID>5435646578</MESSAGEID></TEST>";
The number in the xml string keeps changing so I want to do a string replace and want to make the XML into
<TEST><MESSAGEID></MESSAGEID></TEST>
I am looking for doing something like this but I'm not sure how to get the pattern for the first argument in the replaceAll method.
public class HelloWorld {
public static void main(String[] args) {
String XML = "<MESSAGEID>5435646578</MESSAGEID>";
String newStr = XML.replaceAll("<MESSAGEID>*</MESSAGEID>", "<MESSAGEID></MESSAGEID>");
System.out.println(newStr);
}
}
Upvotes: 1
Views: 684
Reputation: 2153
try replacing your *
in uotmXML.replaceAll("<MESSAGEID>*</MESSAGEID>", ...
with [^<]+
. This will match everything until the <
character
Upvotes: 1
Reputation: 1612
I would use the alphanumeric pattern unless you're absolutely certain it'll just be numeric:
// alphanumeric
String newStr = uotmXML.replaceAll("<MESSAGEID>\w+</MESSAGEID>", "<MESSAGEID></MESSAGEID>");
// digits
String newStr = uotmXML.replaceAll("<MESSAGEID>\d+</MESSAGEID>", "<MESSAGEID></MESSAGEID>");
Upvotes: 2
Reputation: 175
I would use the regex ^<MESSAGEID>(\d+)</MESSAGEID>$
to find the digits (in group 1), if you are guaranteed the format won't change. Otherwise I would use a proper XML library like JAXB or Jackson.
Upvotes: 2
Reputation: 1960
The pattern <MESSAGEID>[0-9]+</MESSAGEID>
would work. If the structure of your input can change, you may want to use an XML parser instead.
Upvotes: 3