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:
"{{(.*?)}}"
{{string}}
:p
or
{{(.*)}}
only numbers inside the {{ }}
{{([0-9])}}
only some characters:
{{([a-zA-Z])}}
这应该工作:
resultString = Regex.Match(subjectString, @"^\{\{(.*?)\}\}$").Groups[1].Value;
I 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.
string strRegex = @"{{(?<String>\w+)}}";
Regex myRegex = new Regex(strRegex);
string strTargetString = @"\n{{string}}";
var match = myRegex.Match(strTargetString);
string str = match.Groups["String"].Value;
The str variable will be the string from bracets
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.