2

How do I form a regular expression to extract variables from a string which are of the format ${variable name}

Lets say I have a string like this :

hello ${ person } welcome to ${ university name}. you are enrolled in ${class}

and I need to extract these from the string

person ,

university name ,

class

3 Answers 3

3

You can use this regex to grab all the values inside ${...}:

\$\{ *([\w -]+) *\}

Java code:

Pattern p = Pattern.compile("\\$\\{ *([\\w -]+) *\\}");

Use a Matcher object to grab all the groups using while(matcher.find()) {...} code snippet.

RegEx Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Pattern p = Pattern.compile("\\$\\{*([\\w -]+)*\\}"); java.util.regex.Matcher m = p.matcher("hello ${person} welcome to ${universityname}. you are enrolled in ${class}"); m.groupCount() gives me 1 and only returns the last variable
As I said in answer you will need to use while(matcher.find()) { System.out.println(matcher.group(1)); }
` while matcher.find(){ System.out.println(matcher.group(0)); } ` worked for me
1

You also can use RegEx that'll find all values in ${}

\b*\u0024\{([\w\s]*)\}\B

where u0024 is a $ in unicode and test in regexplanet

Here is an example of code:

Pattern pattern = Pattern.compile("\\b*\u0024\\{([\\w\\s]*)\\}\\B");
String data = ...//String to parse
Matcher matcher = pattern.matcher(data);
// check all occurrence
while (matcher.find()) {
...
}

Comments

0

You can use this

MessageFormat.format(str, list);

where the str=hello {1} welcome to {2}. you are enrolled in {3}

and the just pass the values in the list

1 Comment

No that is not what i want. First i would want to know what each of the variables is. The string I gave is just an example string . I can have a string like ${university} welcomes ${person} to ${class}. The answer i am looking for is how do i form a regular expression

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.