如何删除正则表达式中的空标签?

时间:2015-10-23 08:04:52

标签: regex

我想删除一些空标记,例如<A/><B/><C/>,....

如何使用Regex删除这些标签?

3 个答案:

答案 0 :(得分:0)

您可以尝试使用此正则表达式:

<[^>]+\/>

<强> Regex Demo

答案 1 :(得分:0)

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

控制台:

<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

答案 2 :(得分:-1)

试试这个正则表达式:

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