Get values between curly braces c#

2019-01-19 15:31发布

问题:

I never used regex before. I was abel to see similar questions in forum but not exactly what im looking for

I have a string like following. need to get the values between curly braces

Ex: "{name}{name@gmail.com}"

And i Need to get the following splitted strings.

name and name@gmail.com

I tried the following and it gives me back the same string.

string s = "{name}{name@gmail.com}";
string pattern = "({})";
string[] result = Regex.Split(s, pattern);

回答1:

Is using regex a must? In this particular example I would write:

s.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)


回答2:

Use Matches of Regex rather than Split to accomplish this easily:

string input = "{name}{name@gmail.com}";
var regex = new Regex("{(.*?)}");
var matches = regex.Matches(input);
foreach (Match match in matches) //you can loop through your matches like this
{
  var valueWithoutBrackets = match.Groups[1].Value; // name, name@gmail.com
  var valueWithBrackets = match.Value; // {name}, {name@gmail.com}
}


回答3:

here you go

string s = "{name}{name@gmail.com}";
s = s.Substring(1, s.Length - 2);// remove first and last characters
string pattern = "}{";// split pattern "}{"
string[] result = Regex.Split(s, pattern);

or

string s = "{name}{name@gmail.com}";
s = s.TrimStart('{');
s = s.TrimEnd('}');
string pattern = "}{";
string[] result = Regex.Split(s, pattern);