Get values between curly braces c#

2019-01-19 14:45发布

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);

3条回答
祖国的老花朵
2楼-- · 2019-01-19 15:28

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}
}
查看更多
Rolldiameter
3楼-- · 2019-01-19 15:34

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

s.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
查看更多
We Are One
4楼-- · 2019-01-19 15:38

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);
查看更多
登录 后发表回答