【问题标题】:Java RegEx: Replace all xml characters with their entity numberJava RegEx:将所有 xml 字符替换为其实体编号
【发布时间】:2013-04-22 11:08:18
【问题描述】:

我正在尝试将我在 ActionScript 中编写的函数移植到 Java,但遇到了一些麻烦。我已经包含了下面的功能。我找到了this response to question #375420,但我真的需要写一个单独的类吗?谢谢。

public static function replaceXML(str:String):String {
  return str.replace(/[\"'&<>]/g, function($0:String):String {
    return StringUtil.substitute('&#{0};', $0.charCodeAt(0));
  });
}

输入

<root><child id="foo">Bar</child></root>

输出

&#60;root&#62;&#60;child id=&#34;foo&#34;&#62;Bar&#60;/child&#62;&#60;/root&#62;

更新

如果有人想知道,这是我的解决方案。谢谢Sri Harsha Chilakapati

public static String replaceXML(final String inputStr) {
  String outputStr = inputStr;
  Matcher m = Pattern.compile("[&<>'\"]").matcher(outputStr);
  String found = "";
  while (m.find()) {
    found = m.group();
    outputStr = outputStr.replaceAll(found,
      String.format("&#%d;", (int)found.charAt(0)));
  }
  return outputStr;
}

【问题讨论】:

    标签: java regex actionscript-3 replace xml-entities


    【解决方案1】:

    您可以为此使用正则表达式。

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
    
    String myString = "<root><child id=\"foo\">Bar</child></root>";
    
    Matcher m = Pattern.compile("[^\\p{L}\\p{N};\"+*/-]").matcher(myString);
    
    while (m.find()) {
        String found = m.group();
        myString = myString.replaceAll(found, "&#" + (int)found.charAt(0) + ";");
    }
    
    System.out.println(myString);
    

    它正在工作。

    输出是

    &#60;root&#62;&#60;child&#32;id&#61;"foo"&#62;Bar&#60;/child&#62;&60;/root&#62;
    

    【讨论】:

    • 我之前尝试过分组但没有成功,虽然我的正则表达式没有你的那么复杂。我会试一试。
    • 因此,您将匹配除以下内容之外的所有内容:字母、数字、分号、双引号、加号、星号、正斜杠和破折号。我对么?无论如何,如果有人感兴趣,我会用我提出的解决方案更新我的问题。
    【解决方案2】:

    Java 是一种面向对象的语言,因此使用对象。通常你可以创建一个 Util 类,例如RegExUtil 并提供一个静态方法来从任何其他类调用该方法。 util 类本身不应该被实例化。您可以使用私有构造函数来实现。

    public class RegExUtil {
    
      private RegExUtil(){
        //do nth.
      }
    
      public static String replaceXML(String input){
        //do sth.
      }
    }
    

    您应该首先查找 Apache Commons,因为它们可能已经为您的目标提供了解决方案,或者至少您了解了 Util 类是如何构成的。

    【讨论】:

    • 我了解 Apache 提供的 JAR 能够实现我在​​问题中提出的要求,但我真的很想看看是否有办法移植我编写的 ActionScript 代码类似的时尚。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 2014-10-04
    • 1970-01-01
    • 2011-05-15
    • 1970-01-01
    相关资源
    最近更新 更多