Frage

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?

War es hilfreich?

Lösung

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

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.

Andere Tipps

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: \\${(.+?)}$

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top