Question

I need to match text between ${ and } Example:

${I need to match this text}

Simple regex \$\\{(.+?)\\} will work fine until I place some of } inside the text

Curly brackets are paired inside the text to match.

Is there any possibility to solve this by means of Regular Expressions?

Was it helpful?

Solution

\$\{((?:\{[^\{\}]*\}|[^\{\}]*)*)\}

If we meet an opening bracket, we look for its pair, and after the closing one we proceed as usual. This can't handle more than one level of nested brackets.

The main building block here in [^\{\}]* - any non-bracket sequence. It can be surrounded by brackets \{[^\{\}]*\} but it might be not (?:\{[^\{\}]*\}|[^\{\}]*). Any count of these sequences can be present, hence * at the end.

Any level of nesting might require a recursive regex, not supported by Java. But any fixed amount can be matched by carefully extending this idea.

OTHER TIPS

Add a $ to end of the ReGex and don't escape it. The dollar sign means it'll check for the previous letter or symbol at the very end.

ReGex: \${(.+?)}$

Java Formatted: \\${(.+?)}$

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top