Objective
I believe you may have encountered this situation, in the development of similar in-Station letter requirements, we often use string templates, such as
Honorable User ${name} ....
The inside ${name}
can be replaced with the user's user name.
The following is a simple implementation of this function using regular expressions:
/**
* Fills strings based on key value pairs, such as ("Hello ${name}", {name: "Xiaoming"})
* output:
* @param content
* @param map
* return
*
/public static string renderstring (string content, map<string, string> Map) {
set< entry<string, string>> sets = Map.entryset ();
For (entry<string, string> entry:sets) {
String regex = "\\$\\{" + entry.getkey () + "\}";
Pattern pattern = pattern.compile (regex);
Matcher Matcher = pattern.matcher (content);
Content = Matcher.replaceall (Entry.getvalue ());
}
return content;
}
A map
key-value pair is stored in, then a collection of key-value pairs is retrieved, and the collection is traversed to render the string
Instance test:
@Test public
void Renderstring () {
String content = "Hello ${name}, 1 2 3 4 5 ${six} 7, again ${name}.";
map<string, string> map = new hashmap<> ();
Map.put ("name", "Java");
Map.put ("Six", "6");
Content = stringhelper.renderstring (content, map);
SYSTEM.OUT.PRINTLN (content);
}
There are two variables that need to be replaced, name
and the six
corresponding values are Java
and 6 respectively, and two are called at the same time name
.
Results:
Summarize
The above is about Java using regular expression to implement ${name} form of the entire contents of the string template, I hope this article on the content of everyone's study or work can bring some help, if you have questions you can message exchange.