what is the regex for matching a string within two curly brackets as in
{{string}}
result should be string.
Do I have to escape both curly brackets?
what is the regex for matching a string within two curly brackets as in
{{string}}
result should be string.
Do I have to escape both curly brackets?
No, actually the following should work just fine:
"{{([^}]*)}}"
Edit:
As pointed out by dtb the expression above fails for a string containing a single } within the double brackets. To handle this case the following example would do a much better job:
"{{((?:}(?!})|[^}])*)}}"
Edit 2: The simplest solution however would probably be the following:
"{{(.*?)}}"
.*? instead of [^}]* - it will not consume the double }} because the ? makes the * reluctant, or lazyI believe this would be the best/simplest possible regex to specifically capture the CONTENTS of the curly brackets:
(?<={{).*?(?=}})
Broken down, this says:
01 (?<={{) # match AFTER two open curly brackets
02 .*? # match anything, but BE LAZY ABOUT IT
03 (?=}}) # until there are two closing curly brackets
With this expression, the ENTIRE match will be the contents of the curly brackets, and the curly brackets will be left in place/ignored
To match the entire curly-bracketed expression, use the following:
01 {{ # match two open curly brackets
02 .*? # match anything, but BE LAZY ABOUT IT
03 }} # match two closing curly brackets
If you want to support multiple lines inside the curly brackets, use [\s\S]*? instead of .*? in the part on line 02, or specify the 'singleline' option for the regex parser (DOTALL in Java, etc, etc, etc...).
It does not reject instances like some text {{{inside}}} other test and may produce undesired results - if those are possible, please ask for a stronger expression and specify several cases of what should and should not be matched.
Singleline, not Multiline. Very common mistake--it comes of expecting the names to make sense. ;) As described here, Singleline changes the meaning of the . metacharacter, while Multiline changes the meaning of the anchors, ^ and $. Aside from that, this answer looks pretty good to me; not worthy of a downvote.