Matching {{string}} in C # regex

what is a regular expression for matching strings in two curly braces, as in

{{string}} 

the result should be string .

Should I avoid both curly braces?

+6
source share
5 answers

No, actually the following should work fine:

 "{{([^}]*)}}" 

Edit: As indicated in dtb, the expression above is not suitable for a string containing one } in double brackets. To handle this case, the following example could do a much better job:

 "{{((?:}(?!})|[^}])*)}}" 

Edit 2: The simplest solution would probably be the following:

 "{{(.*?)}}" 
+6
source
 {{string}} 

: R

or

 {{(.*)}} 

only numbers inside {{}}

 {{([0-9])}} 

only some characters:

 {{([a-zA-Z])}} 
+2
source

This should work:

 resultString = Regex.Match(subjectString, @"^\{\{(.*?)\}\}$").Groups[1].Value; 
+2
source

I believe this would be the best / easiest possible regex for a specific grab of braces:

 (?<={{).*?(?=}}) 

Broken, it 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 consist of curly braces, and the curly braces will remain in place / ignored

To match the entire expression in braces, 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 curly braces, use [\s\S]*? instead of .*? in part on line 02 or specify the "singleline" parameter for the regex parser (DOTALL in Java, etc.)., etc. etc.).

It does not reject instances such as some text {{{inside}}} other test and may produce unwanted results - if possible, ask for a stronger expression and indicate several cases of what should and should not be matched.

+2
source
  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 a string from braces

+1
source

Source: https://habr.com/ru/post/899634/


All Articles