1

Regex to fetch strings enclosed inside "${VALUE}" using java regular expression throws exception

public static void main(String[] args) {

        String test = "Report for ${PROCESS_NAME} with status ${PROCESS_STATUS}";
        String[] results = test.split("\\${([^\\{\\}]*)\\}");
        for (String result : results) {
            System.err.println(result);
        }
    }



Exception in thread "main" java.util.regex.PatternSyntaxException: Illegal repetition near index 1
\${([^\{\}]*)\}
 ^
    at java.util.regex.Pattern.error(Unknown Source)
    at java.util.regex.Pattern.closure(Unknown Source)
    at java.util.regex.Pattern.sequence(Unknown Source)

Expected array: results = PROCESS_NAME, PROCESS_STATUS;

Input test string is not fixed length. Whats wrong in the regex.

1
  • Escape the Opening curly bracket after the escaped Dollar symbol Commented Apr 16, 2014 at 1:44

3 Answers 3

2

I suggest this solution

    Matcher m = Pattern.compile("\\$\\{(.+?)\\}").matcher(test);
    while(m.find()) {
        System.out.println(m.group(1));
    }
Sign up to request clarification or add additional context in comments.

1 Comment

. is represent any character. i think below expression will be better: "\\$\\{(\\w+?)\\}"
1

You need to escape { as well:

test.split("\\$\\{([^\\{\\}]*)\\}")

Also you don't have to escape {} inside character class:

test.split("\\$\\{([^{}]*)\\}")

3 Comments

Generates - "Summary Report for", "with status". But i am expecting the string inside the Curly braces - "PROCESS_NAME", "PROCESS_STATUS"
This is because you split by it. If you need to match regexp, then use Matcher.
Thanks Ivan i should have used Matcher.
1

You probably lost one '\' in your regexp. It should look like that:"\\$\\{([^\\{\\}]*)\\}".

However, split() method will not do what you want. As marked here

The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.

You need to find substrings matching specified pattern. That could be done like that:

String patternString = "\\$\\{([^\\{\\}]*)\\}";
List<String> results = new ArrayList<String>();

String test = "Report for ${PROCESS_NAME} with status ${PROCESS_STATUS}";

Pattern pattern = Pattern.compile(patternString);
Matcher matcher = pattern.matcher();

while(matcher.find()) {
     results.add(matcher.group(1));
}

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.