我们可以使用正则表达式来匹配占位符,然后从映射中取出对应的值进行替换。 // 待解析的字符串Stringinput="My name is {name} and I am {age} years old.";// 匹配占位符的正则表达式Patternpattern=Pattern.compile("\\{([a-zA-Z]+)\\}");Matchermatcher=pattern.matcher(input);StringBuffersb=newString...
项目中常常需要解析字符串模板,比如user:{userId}:{userType}用于redis的key等,比较常见的做法就是使用String.format("user:%s:%s", 1, 1)方法,但个人感觉那样的模板不够明了,而使用模板解析器可更好地有助于解析此类字符串。可使用map用于解析,也可使用对象进行解析,也可使用类似String.format可变参数进行解析...