Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中用字符串表示自定义属性_Java_Regex - Fatal编程技术网

在java中用字符串表示自定义属性

在java中用字符串表示自定义属性,java,regex,Java,Regex,我想用一个简单的字符串来表示一些自定义属性,比如我们如何在XML/JSON中使用属性 示例: some_string1${object1.property1}some_string2${object2.property1} 这就是我正在尝试的: package com.foo.bar; public class CustomStringFormator { public String formatString(String input) { String output = n

我想用一个简单的字符串来表示一些自定义属性,比如我们如何在XML/JSON中使用属性

示例:

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}
标记


请给我您的建议。

您的实际问题是什么?在formatString方法中,我希望解决方案将${property}标记替换为getValueForProperty(property)返回的值。
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;
}