سؤال

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