简体   繁体   中英

How remove empty tags in Regex?

I want to delete some empty tags, for example <A/> , <B/> , <C/> ,....

How to remove these tags using Regex?

You can try to use this regex:

<[^>]+\/>

Regex Demo

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HelloWorld{

    public static void main(String[] args) {
        final String regex1 = "<([a-zA-Z0-9-\\_]*)[^>]*/>";
        final String regex2 = "<([a-zA-Z0-9-\\_]*)[^>]*>\\s*</\\1>";

        String xmlString = " <xml><A>bla</A><B></B><B/><D><E><G><H/></G></E><F></F></D></xml>";

        System.out.println(xmlString);

        final Pattern pattern1 = Pattern.compile(regex1);
        final Pattern pattern2 = Pattern.compile(regex2);

        Matcher matcher1;
        Matcher matcher2;
        do {
            xmlString = xmlString.replaceAll(regex1, "").replaceAll(regex2, "");
            matcher1 = pattern1.matcher(xmlString);
            matcher2 = pattern2.matcher(xmlString);
        } while (matcher1.find() || matcher2.find());

        System.out.println(xmlString);
    }
}

Console:

<xml>
    <A>bla</A>
    <B></B>
    <B/>
    <D>
        <E>
            <G>
                <H/>
            </G>
        </E>
        <F></F>
    </D>
</xml>

<xml>
    <A>bla</A>
</xml>

Online demo here

试试这个正则表达式:

/<[^\/>][^>]*><\/[^>]+>/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM