2015-11-10 34 views
0

我想用一個普通字符串表示一些自定義屬性,比如我們如何在XML/JSON中使用屬性。表示java中字符串中的自定義屬性

例子:

some_string1${object1.property1}some_string2${object2.property1} 

這就是我想:

package com.foo.bar; 

public class CustomStringFormator { 
    public String formatString(String input) { 
    String output = null; 
    // Here I need solution to extract ${} patterns using regex and replace 
    // the substitutions for that by calling getValueForProperty() method 
    // example getValueForProperty("object1.property1") return value1 
    return output; 
} 

private String getValueForProperty(String property) { 
    String value = null; 
    // some known logic 
    return value; 
} 

public static void main(String[] args) { 
    String output = new CustomStringFormator() 
      .formatString("some_string1_${object1.property1}_some_string2${object2.property1}"); 
    // output will be like 
    // some_string1_value1_some_string2_value2 
} 
} 

我使用普通的字符串,而不是其他的文字表示,因爲我想優化這個操作最大。

在formatString方法中,我想要一個解決方案用getValueForProperty(property)返回的值替換${property}標記。

請給我你的建議。

+0

您是什麼實際問題或疑問? – glethien

+0

在formatString方法中,我希望解決方案使用getValueForProperty(property)返回的值替換$ {property}標記。 –

回答

2
public String formatString(String input) { 
    Pattern pattern = Pattern.compile("\\$\\{\\s*(\\w+\\.\\w+)\\s*\\}"); 
    Matcher matcher = pattern.matcher(input); 
    while(matcher.find()){ 
     String key = matcher.group(1); 
     String value = getValueForProperty(key);// object1.property1,object2.property1 
     String output = input.replace(matcher.group(),value); 
     input = output; 
    } 
    return output; 
} 
相關問題