Home > Software engineering >  Extracting contents of placeholders inside curly braces prefixed with dollar symbol
Extracting contents of placeholders inside curly braces prefixed with dollar symbol

Time:11-19

Lets say I have a string "lore epsum dimsum ${ITEM_NAME} wonton kimchi".

I have created a regex that can extract ${ITEM_NAME} from anywhere in the string. That regex is, .{(.*.*)}.

How can I customize this regex to extract just the string between ${} which is ITEM_NAME?

CodePudding user response:

With {(.*.*)} pattern, you extract any substrings between the leftmost { and rightmost }.

You need

\$\{([^{}]*)\}

In Java:

String regex = "\\$\\{([^{}]*)\\}";

See the regex demo.

If there is an explicit requirement to only match alphanumeric/underscore chars inside ${...}, you can replace [^{}]* with \w / \w* pattern (doubling the backslashes in Java string literal).

See the Java demo:

import java.util.*;
import java.util.regex.*;

class Test
{
    public static void main (String[] args) throws java.lang.Exception
    {
        String text = "lore epsum dimsum ${ITEM_NAME} wonton kimchi ${ITEM_NAME_2}";
        Pattern p = Pattern.compile("\\$\\{([^{}]*)}");
        Matcher m = p.matcher(text);
        List<String> res = new ArrayList<>();
        while(m.find()) {
            res.add(m.group(1));
        }
        System.out.println(res);
    }
}

Output:

[ITEM_NAME, ITEM_NAME_2]
  • Related