문제

I need to parse text, and put varibales into it. Something like that:

lorem ${var} dolor sit amet consectetur adipiscing elit

end put String var = "ipsum" insted of ${var}

What the easyest way to do that? I'm going to use regexp and matcher. But may be spring (or something else) already has this functionality?

도움이 되었습니까?

해결책

The Java standard class MessageFormat is relatively close to what you want, but it doesn't handle arbitrary placeholder names. If that is needed, your best bet really are regular expressions. If you don't think they are fast, I advise you to measure before turning your back on them. Here's an outline:

final Map<String, String> vars = new HashMap<String, String>();
vars.put("var", "ipsum");
final String s = "lorem ${var} dolor sit amet consectetur adipiscing elit";
final Matcher m = Pattern.compile("\\$\\{(.*?)\\}").matcher(s);
final StringBuffer b = new StringBuffer(s.length());
while (m.find()) m.appendReplacement(b, vars.get(m.group(1)));
m.appendTail(b);
System.out.println(b);

다른 팁

String has a built-in wrapper for a regex expression: String replaceAll(String regex, String replacement)

try:

 String result = "lorem ${var} dolor sit amet consectetur adipiscing elit".replaceAll("\\$\\{var\\}", "ipsum");
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top