1

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);
    }
}
2
  • 1
    try replacing your * in uotmXML.replaceAll("<MESSAGEID>*</MESSAGEID>" with [^<]+. This will match everything until the < character Commented Aug 23, 2019 at 19:27
  • This worked for me. If you would like to add it as an answer as opposed to a comment, I will accept this answer. Commented Aug 23, 2019 at 19:54

4 Answers 4

3

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

2

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>");

Comments

1

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

Comments

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.