我不认为正则表达式是这项工作的正确工具,但这样的东西有时会“工作”。
String text =
" <rect width='10px' height ='20px'/> \n" +
" <rect width='20px' height ='22px'/> \n" +
" <circle radius='20px' height ='22px'/> \n" +
" <square/> <rectangle></rectangle> \n" +
" <foo @!(*#&^#@/> <bar (!@*&(*@!#> </whatever>";
System.out.println(
text.replaceAll("<([a-z]+)([^>]*)/>", "<$1$2></$1>")
);
上面的 Java 代码段打印:
<rect width='10px' height ='20px'></rect>
<rect width='20px' height ='22px'></rect>
<circle radius='20px' height ='22px'></circle>
<square></square> <rectangle></rectangle>
<foo @!(*#&^#@></foo> <bar (!@*&(*@!#> </whatever>
正则表达式是这样的(另见 rubular.com):
/<([a-z]+)([^>]*)\/>/
本质上,我们尝试捕获我们希望是第 1 组中的标签名称,以及直到第/>
2 组中的所有其他内容,并在我们的替换中使用这些捕获的字符串。
参考