C # regex. Everything inside curly braces {} and mod (%) charaters

I am trying to get values ​​between {} and %% in the same Regex. This is what I still have. I can successfully get the values ​​individually for each, but I was curious to know how I can combine both.

var regex = new Regex(@"%(.*?)%|\{([^}]*)\}");

String s = "This is a {test} %String%. %Stack% {Overflow}";

The expected response for the specified string

test
String
Stack
Overflow

Individual Regular Expression

@"%(.*?)%" gives me String and Stack
@"\{([^}]*)\}" gives me test and Overflow

Below is my code.

var regex = new Regex(@"%(.*?)%|\{([^}]*)\}");
var matches = regex.Matches(s); 
foreach (Match match in matches) 
{
    Console.WriteLine(match.Groups[1].Value);
}
+4
source share
5 answers

Sometimes the capture is in group 1, and sometimes in group 2, because you have two pairs of parentheses.

The source code will work if you do this instead:

Console.WriteLine(match.Groups[1].Value + match.Groups[2].Value);

because one group will be an empty string and the other will be the value that interests you.

+1

.

String s = "This is a {test} %String%. %Stack% {Overflow}";
var list = Regex.Matches(s, @"\{(?<name>.+?)\}|%(?<name>.+?)%")
           .Cast<Match>()
           .Select(m => m.Groups["name"].Value)
           .ToList();
+3

, , , ​​ .NET regex:

(?:(?<p>%)|(?<b>{))(?<v>.*?)(?(p)%|})

regex

:

  • (?:(?<p>%)|(?<b>{)) - "p" % ( ) "b" () {
  • (?<v>.*?) - "v" () ( , RegexOptions.Singleline) , ( *? )
  • (?(p)%|})- conditional expression meaning: if the group "p" was matched %, match , else, match }.

enter image description here

C # demo :

var s = "This is a {test} %String%. %Stack% {Overflow}";
var regex = "(?:(?<p>%)|(?<b>{))(?<v>.*?)(?(p)%|})";
var matches = Regex.Matches(s, regex, RegexOptions.Singleline); 
// var matches_list = Regex.Matches(s, regex, RegexOptions.Singleline)
//                 .Cast<Match>() 
//                 .Select(p => p.Groups["v"].Value)
//                 .ToList(); 
// Or just a demo writeline
foreach (Match match in matches) 
    Console.WriteLine(match.Groups["v"].Value);
+2
source
@"[\{|%](.*?)[\}|%]"

Idea:

{ or %
anything
} or %
0
source

I think you should use a combination of conditional and nested groups:

((\{(.*)\})|(%(.*)%))
0
source

All Articles