【问题标题】:Java regex to remove all the characters after space in the end tag of an xmlJava正则表达式删除xml结束标记中空格后的所有字符
【发布时间】:2017-06-21 03:41:50
【问题描述】:

我有一个以下格式的 XML 文件。

<?xml version="1.0" encoding="UTF-8"?>
<SampleData ID="Test" Password="Test">
<STATUS operation=”remove”>EXPIRED</STATUS operation=”remove”>
<PRIVILEGE operation=”remove”>12345</PRIVILEGE operation=”remove”>
<userID>ABC123</userID>
<PROFILE operation=”remove”>DEFAULT</PROFILE operation=”remove”>
</SampleData>

在此 XML 中,我不希望空格后的结束标记中有任何文本。例如,如果您考虑结束标签&lt;/STATUS operation=”remove”&gt;,我只想让它显示为&lt;/STATUS&gt;。如果任何结束标签中没有空格,则该标签可以保持不变。此外,在任何情况下,开始标签都将保持不变。

有人可以建议我任何可以解析整个 XML 并检查每个结束标记的正则表达式,以便我可以删除这些标记中空格后的任何字符。

【问题讨论】:

  • 多么奇怪的 XML,我从未在结束标记中看到过属性。
  • 如果不是,请不要将其称为 XML。处理声称是 XML 但不是 XML 的内容的最佳方法是修复创建它的程序中的错误。

标签: java regex xml


【解决方案1】:

这是实现此目的的一种方法:

final String regex = "(<\\/.*)\\ (.*)>";

final String string = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n"
         + "<SampleData ID=\"Test\" Password=\"Test\">\n"
         + "<STATUS operation=”remove”>EXPIRED</STATUS operation=”remove”>\n"
         + "<PRIVILEGE operation=”remove”>12345</PRIVILEGE operation=”remove”>\n"
         + "<userID>ABC123</userID>\n"
         + "<PROFILE operation=”remove”>DEFAULT</PROFILE operation=”remove”>\n"
         + "</SampleData>";

final String subst = "$1>";

final Pattern pattern = Pattern.compile(regex);
final Matcher matcher = pattern.matcher(string);

// The substituted value will be contained in the result variable
final String result = matcher.replaceAll(subst);

System.out.println(result);

输出

<?xml version="1.0" encoding="UTF-8"?>
<SampleData ID="Test" Password="Test">
<STATUS operation=”remove”>EXPIRED</STATUS>
<PRIVILEGE operation=”remove”>12345</PRIVILEGE>
<userID>ABC123</userID>
<PROFILE operation=”remove”>DEFAULT</PROFILE>
</SampleData>

在这里测试:Regex 101

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2011-09-08
    • 1970-01-01
    • 2021-01-24
    • 2020-03-30
    相关资源
    最近更新 更多