Get values between curly braces c#

强颜欢笑 提交于 2019-12-17 20:07:49

问题


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


来源:https://stackoverflow.com/questions/17379482/get-values-between-curly-braces-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!