我將給出包含格式化「屬性」的字符串;也就是說,封裝在標準「$ {」和「}」令牌內的字符串:搜索並替換Java字符串中的格式化屬性
「這是$ {string}的$ {example},我可能是$ {given}。」
我也將有一個HashMap<String,String>
包含替換爲每個可能的格式屬性:
HashMap Keys HashMapValues
===========================================
bacon eggs
ham salads
因此,鑑於以下字符串:
「我最喜歡吃$ {臘肉}和$ {ham}。「
我可以給這個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
無法匹配任何屬性。
所以我的第一個問題是:這個正則表達式應該是什麼?
一旦我已經過去了,我不知道如何在將「$ {bacon}」變成「雞蛋」等任何想法?提前致謝!
試圖解決這個問題,正則表達式(如果可能的話...)是一個跑位練習,「在現實世界「你應該使用像例如引擎http://freemarker.sourceforge.net –