p0tta
p0tta

Reputation: 1651

Java String Replace on an XML pattern

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

Answers (4)

dvo
dvo

Reputation: 2153

try replacing your * in uotmXML.replaceAll("<MESSAGEID>*</MESSAGEID>", ... with [^<]+. This will match everything until the < character

Upvotes: 1

Victor P
Victor P

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

ansjob
ansjob

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

IronMan
IronMan

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

Related Questions