Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java regex: replace ${var}

Tags:

java

regex

I'm trying to replace a String like:

Hello, my name is ${name}. I am ${age} years old.

with

Hello, my name is Johannes. I am 22 years old.

Variables are stored in a HashMap. My code so far:

private void replace() {
        HashMap<String, String> replacements = new HashMap<String, String>();
        replacements.put("name", "Johannes");
        replacements.put("age", "22");

        String text = "Hello, my name is {name}. I am {age} years old.";
        Pattern pattern = Pattern.compile("\\{(.+?)\\}");
        Matcher matcher = pattern.matcher(text);

        StringBuilder builder = new StringBuilder();
        int i = 0;
        while (matcher.find()) {
            String replacement = replacements.get(matcher.group(1));
            builder.append(text.substring(i, matcher.start()));
            if (replacement == null) {
                builder.append("");
            } else {
                builder.append(replacement);
                i = matcher.end();
            }
        }
        builder.append(text.substring(i, text.length()));
        System.out.println(builder);
    }

It's wokring fine, but I would like to replace ${var} and not {var}. Changing it to Pattern.compile("\${(.+?)\}"); will throw an PatternSyntaxException: "Illeagal repetition".

Escaping the $ (Pattern.compile("\\${(.+?)\}") will cause an compiling error.

So How to I have to change my Pattern to accept ${var} instead of {var}

like image 494
Johannes Staehlin Avatar asked Feb 21 '23 06:02

Johannes Staehlin


1 Answers

The { character is reserved in most regex libraries for repetition along the lines of {n,m}. Try the regex

\\$\\{(.+?)\\}
like image 117
Konstantin Tarashchanskiy Avatar answered Mar 03 '23 04:03

Konstantin Tarashchanskiy