正規表現がこの仕事に適したツールだとは思いませんが、このようなものが「うまくいく」場合があります。
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 までのその他すべてをキャプチャして、これらのキャプチャされた文字列を置換で使用します。
参考文献