3

I am not soo good in RegEx. Can somebody help me to to replace

<MessageParam name="0" desc="Source Queue" />

with

<MessageParam name="0" desc="Source Queue"></MessageParam>

using regular expression

2
  • 1
    You should try using JDom instead. Commented Dec 25, 2012 at 5:55
  • don't use regex to parse HTML Commented Jan 9, 2023 at 22:35

4 Answers 4

13

Regex to match:

(<\s*MessageParam[^>]*)/\s*>

Replacement string:

$1></MessageParam>

You may need to escape the \ character (add an extra \ before it).

I assume > does not appear in the value for the attributes, and the XML is valid.

More generalized version:

Regex to match:

<\s*([^\s>]+)([^>]*)/\s*>

Replacement string:

<$1$2></$1>

For this one, I'm not sure of all the assumptions that I have made. But I still assume > does not appear in the value for the attributes, and the XML is valid.

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

2 Comments

I'm not sure if XML parser can change the type of closing tag. It is better to use XML parser to do so if possible.
For those of you looking for the inverse of this question, you can use the following code to replace open/close empty tags with self-closing tags. Find: <([A-Z][A-Z0-9]*)\b[^>]*>(.*?)</\1> Replace it with: <$1/> (Thanks to thetopsites.net/article/51312414.shtml)
6

Regex

<(\w+)(.+?)/>

replace with

<$1$2></$1>

4 Comments

This just really helped me, as the accepted answer produced some occasionally strange results
This doesn't work on nested DOM elements, unfortunately.
Perfect! Exactly what I was looking for. Just use this in Notepad++ with the find and replace feature and you are done :)
saved me hours of wasted effort
0
public static void format(String xmlNode) {
    Pattern patt = Pattern.compile("(<MessageParam[^>]*)(\\s*/>)");
    Matcher mattcher = patt.matcher(xmlNode);
    while (mattcher.find()){
        String result = mattcher.replaceAll("$1></MessageParam>");
        System.out.println(result);
    }
}

3 Comments

A simple replaceAll in String class will do, not sure why you go through all the trouble of writing Pattern/Matcher loop.
nhahtdh - I don't understand how a replaceAll will help if i have multiple strings with different 'desc'
xmlString.replaceAll("(<MessageParam[^>]*)(\\s*/>)", "$1></MessageParam>");
0

This worked for me:

xmlString.replaceAll("<(\\w*:*\\w+)/>", "<$1></$1>");

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

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.