我想删除一些空标记,例如<A/>
,<B/>
,<C/>
,....
如何使用Regex删除这些标签?
答案 0 :(得分:0)
答案 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>
答案 2 :(得分:-1)
试试这个正则表达式:
/<[^\/>][^>]*><\/[^>]+>/