1

ActionScript で記述した関数を Java に移植しようとしていますが、少し問題があります。以下の関数を含めました。質問 #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;

アップデート

誰かが疑問に思っている場合、これが私の解決策です。シュリ・ハルシャ・チラカパティに感謝します。

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;
}
4

2 に答える 2

1

Java はオブジェクト指向言語であるため、オブジェクトを操作します。通常、Util クラスを作成しRegExUtil、静的メソッドを提供して他のクラスからメソッドを呼び出すことができます。util クラス自体はインスタンス化しないでください。これは、プライベート コンストラクターを使用して実現できます。

public class RegExUtil {

  private RegExUtil(){
    //do nth.
  }

  public static String replaceXML(String input){
    //do sth.
  }
}

最初に Apache Commons を検索する必要があります。これは、目的のソリューションが既に提供されているか、少なくとも Util クラスがどのように構成されているかがわかるためです。

于 2013-04-22T11:16:10.497 に答える
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;
于 2013-04-22T11:29:41.953 に答える