String – replace strsubstitute with JRE Library

I'm currently using org apache. commons. lang.text. Strsubstitute:

Map m = ...
substitutor = new StrSubstitutor(m);

result = substitutor.replace(input);

Given that I want to remove common Lang dependencies from my project, what is the working and concise implementation of strsubstitutor using the standard JRE library?

be careful:

Strsubstitute works as follows:

Map map = new HashMap();
map.put("animal","quick brown fox");
map.put("target","lazy dog");
StrSubstitutor sub = new StrSubstitutor(map);
String resolvedString = sub.replace("The ${animal} jumped over the ${target}.");

Succumb to resolvestring = "the fast brown fox jumps over the lazy dog."

Solution

If the performance is not a priority, you can use the appendreplacement method of the matcher class:

public class StrSubstitutor {
    private Map<String,String> map;
    private static final Pattern p = Pattern.compile("\\$\\{(.+?)\\}");

    public StrSubstitutor(Map<String,String> map) {
        this.map = map;
    }

    public String replace(String str) {
        Matcher m = p.matcher(str);
        StringBuilder sb = new StringBuilder();
        while (m.find()) {
            String var = m.group(1);
            String replacement = map.get(var);
            m.appendReplacement(sb,replacement);
        }
        m.appendTail(sb);
        return sb.toString();
    }
}

A higher performance but uglier version, just for fun:)

public String replace(String str) {
        StringBuilder sb = new StringBuilder();
        char[] strArray = str.tocharArray();
        int i = 0;
        while (i < strArray.length - 1) {
            if (strArray[i] == '$' && strArray[i + 1] == '{') {
                i = i + 2;
                int begin = i;
                while (strArray[i] != '}') ++i;
                sb.append(map.get(str.substring(begin,i++)));
            } else {
                sb.append(strArray[i]);
                ++i;
            }
        }
        if (i < strArray.length) sb.append(strArray[i]);
        return sb.toString();
    }

According to my test, it is about twice as fast as the regular expression version and three times faster than the Apache commons version Therefore, normal regular expressions are actually more optimized than the Apache version Of course, it's usually not worth it Just for fun, let me know if you can make it more optimized

Editor: as @kmek pointed out, there is a warning The Apache version will be resolved over time For example, if ${animal} maps to ${dog} and the dog maps to the golden retriever, the Apache version maps ${animal} to the golden retriever As I said, you should use the library as much as possible If you have a special constraint that does not allow the use of libraries, use only the above solution

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>