简体   繁体   English

用自定义字符串替换美元符号($)变量的Java EE方法

[英]Java EE method to replace dollar sign ($) variables with custom string

Is there a pre-written method to replace dollar-sign name variables in a string with a predefined constant? 是否有预先编写的方法用预定义的常量替换字符串中的美元符号名称变量?

For example, the following code : 例如,以下代码:

Map<String, Object> myVars = new TreeMap<String, Object>();
String str = "The current year is ${currentYear}.";
myVars.put("currentYear", "2014");
System.out.println(Replacer.replaceVars(str, myVars));

... would have this output: ...会有这样的输出:

The current year is 2014.

Have a look at the MessageFormat class. 看看MessageFormat类。 Your example would look like this: 您的示例如下所示:

int currentYear = 2014;
String str = "The current year is {0}.";
str = MessageFormat.format(str, currentYear);

This is probably the best version, but you could always use a regex as well: 这可能是最好的版本,但你总是可以使用正则表达式:

public String format (String input, Map<String, String> replacement)
{
    for (String key : replacement.keySet())
        input = input.replaceAll("\\${"+replacement+"}", replacement.get(key));
    return input;
}

Spring does this too if you need to support more advanced use cases. 如果您需要支持更高级的用例,Spring也会这样做。 I was able to utilize code from the following class for my use cases. 我能够将以下类中的代码用于我的用例。 See the parseStringValue method. 请参阅parseStringValue方法。

https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java https://github.com/spring-projects/spring-framework/blob/master/spring-core/src/main/java/org/springframework/util/PropertyPlaceholderHelper.java

In your case, you need to pass in a PlaceholderResolver that uses your Map to resolve the placeholder. 在您的情况下,您需要传入一个PlaceholderResolver ,它使用您的Map来解析占位符。

I am not aware of any standard Java class which would support this behaviour but writing your tool wouldn't be so hard. 我不知道任何标准的Java类会支持这种行为,但编写你的工具并不会那么难。 Here is example of such solution: 以下是此类解决方案的示例:

class Replacer {
    private static Pattern pattern = Pattern.compile("\\$\\{(?<key>[^}]*)\\}");

    public static String replaceVars(String format, Map<String, ?> map) {
        StringBuffer sb = new StringBuffer();
        Matcher m = pattern.matcher(format);
        while (m.find()) {
            String key = m.group("key");
            if (map.containsKey(key)) {//replace if founded key exists in map
                m.appendReplacement(sb, map.get(key).toString());
            } else {//do not replace, or to be precise replace with same value
                m.appendReplacement(sb, m.group());
            }
        }
        m.appendTail(sb);

        return sb.toString();
    }
}

We could take advantage of default method getOrDefault introduced in Java 8 to Map interface and replace 我们可以利用Java 8中引入的默认方法getOrDefault来映射接口并替换

while (m.find()) {
    String key = m.group("key");
    if (map.containsKey(key)) {//replace if founded key exists in map
        m.appendReplacement(sb, map.get(key).toString());
    } else {//do not replace, or to be precise replace with same value
        m.appendReplacement(sb, m.group());
    }
}
m.appendTail(sb);

with

while (m.find()) 
    m.appendReplacement(sb, map.getOrDefault(m.group("key"), m.group()));
m.appendTail(sb);

But to be able to use this method we first would need to specify type of value in map - in other words we would need to change type of accepted Map from Map<String, ?> map to type like Map<String, String> map . 但是为了能够使用这个方法,我们首先需要在map中指定值的类型 - 换句话说,我们需要将Map<String, ?> map中接受的Map的类型更改为类型,如Map<String, String> map

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM