1

I am trying to parse out the following using Regexes in Java.

My Test String consists of strings within "${}" like for ex: "Test ${template} in ${xyz} : ${abc}"

I am trying to use the regex of the form (\$\{[^\}]+\}) to match it. The current regex does not match anything in the test string.

If I add (.*?)(\$\{[^\}]+\})(.*?) to make it ungreedy, it is really not consistent in giving me whatever I want to match.

What is the issue with my regex? How do I fix it?

6
  • I do have escaped the $ and flower braces. Commented Sep 7, 2011 at 11:09
  • like this "(.*?)(\\$\\{[^\\}]+\\})(.*?)" Commented Sep 7, 2011 at 11:10
  • Can you show ready-to-run example code? Commented Sep 7, 2011 at 11:10
  • 1
    @Sachin: "flower braces" is new to me :) Commented Sep 7, 2011 at 11:10
  • your regex works fine in JavaScript, so it is probably an escaping issue Commented Sep 7, 2011 at 11:13

6 Answers 6

6

Most of the time when someone asks regular expression questions I ask them to at least consider Commons Lang StringUtils:

String[] names = substringsBetween(theString, "${", "}");
Sign up to request clarification or add additional context in comments.

Comments

3
public static void main(String[] args) throws Exception {

    String test = "Test ${template} in ${xyz} : ${abc}";

    Matcher m = Pattern.compile("\\$\\{[^\\}]+\\}").matcher(test);

    while (m.find())
        System.out.println(m.group());
}

Outputs:

${template}
${xyz}
${abc}

Comments

1

You might have to escape the braces as well:

jcomeau@intrepid:/usr/src/clusterFix$ python
Python 2.6.7 (r267:88850, Jun 13 2011, 22:03:32) 
[GCC 4.6.1 20110608 (prerelease)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> s = 'Test ${template} in ${xyz} : ${abc}'
>>> re.compile('\$\{[^}]+\}').findall(s)
['${template}', '${xyz}', '${abc}']

Comments

1
    String test = "Test ${template} in ${xyz} : ${abc}";
    Pattern p = Pattern.compile("\\$\\{[^}]+\\}");
    Matcher matcher = p.matcher(test);
    while (matcher.find()) {
        System.out.println(matcher.group());
    }

Comments

0
        String ip="Test ${template} in ${xyz}";
        Pattern p = Pattern.compile("\\{.*?\\}");
        Matcher m =p.matcher(ip);
        while(m.find())
        {
            System.out.println(m.group());
        }

Comments

0

One slash isn't enough. You need two slashes.

Try this regex:

\\$\\{.+\\}

It checks for strings with ${ and } surrounding text. This filters out blank strings (${}) and anything which isn't closed properly.

If you want to check for text infront and behind, try .+\\$\\{.+\\}.+

Comments

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.