書式付きの「プロパティ」を含む文字列が与えられます。Java文字列内の書式付きプロパティの検索と置換
"これは私が$ {given}になるかもしれない$ {string}の$ {example}です"という文字列が標準の "$ {"と "}"トークンの内部にカプセル化されています。
私はまた、それぞれの可能なフォーマットされたプロパティのHashMap<String,String>
含む置換を持つことになります。
HashMap Keys HashMapValues
===========================================
bacon eggs
ham salads
だから、以下の文字列与えられた:「私は$ {ベーコンを}食べるのが好き
をと$ {ハム}。
私はに変換しますJavaメソッドにこれを送信することができます。
「私は卵とサラダを食べるのが好き。」ここで
私の最高の試みだ:私はこれを実行すると
System.out.println("Starting...");
String regex = "$\\{*\\}";
Map<String,String> map = new HashMap<String, String>();
map.put("bacon", "eggs");
map.put("ham", "salads");
String sampleString = "I like ${bacon} and ${ham}.";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(sampleString);
while(matcher.find()) {
System.out.println("Found " + matcher.group());
// Strip leading "${" and trailing "}" off.
String property = matcher.group();
if(property.startsWith("${"))
property = property.substring(2);
if(property.endsWith("}"))
property = property.substring(0, property.length() - 1);
System.out.println("Before being replaced, property is: " + property);
if(map.containsKey(property))
property = map.get(property);
// Now, not sure how to locate the original property ("${bacon}", etc.)
// inside the sampleString so that I can replace "${bacon}" with
// "eggs".
}
System.out.println("Ending...");
、私はエラーを取得していないが、ちょうど「開始...」と「エンディング...」の出力を参照してください。これは私の正規表現が間違っていることを示しているので、Matcher
はどのプロパティとも一致することができません。
私の最初の質問は:この正規表現は何でしょうか?
これを過ぎると、「$ {ベーコン}」を「卵」などに変更した後に文字列の置換を行う方法がわかりません。前もって感謝します!
(可能ならば全く...)アカデミック行使され、「リアルタイムで世界 "のようなエンジンを使うべきですhttp://freemarker.sourceforge.net –