如何用与模式匹配的新值替换String?

时间:2015-11-05 01:53:08

标签: java regex xml

应用程序接收XML消息(输入),如:

String input = "<?xml version="1.0" encoding="utf-8"?>
<message>
   <property name="name1" value="value1" type="A"/>
   <property name="name2" value="valu%@1" type="B"/>
   <property name="name3" value="my value=\"test\"" type="B"/>
</message>";

我需要解析这个XML(String)并确保所有值都是XML清理的。我使用Apache的StringEscapeUtils.escapeXml()来确保所有特殊字符都被编码。

String regex = "(?<=value=\")([^\"]+).*?(?=\" type=\")";
Pattern pattern = Pattern.compile (regex);

并且

Matcher m = pattern.matcher (input);
while (matcher.find()) {
  String oldValue = m.group(1);
  String newValue = StringEscapeUtils.escapeXml(oldValue);
  ??
}

我只希望对每个值进行消毒并单独更换,而不仅仅是出现任何值。要么它不起作用,要么我得到IllegalArgumentException:使用replaceAll或replaceFirst时非法的组引用。

最有效的方法是什么?

谢谢 -

0 个答案:

没有答案