سؤال

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);
هل كانت مفيدة؟

المحلول 2

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

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

نصائح أخرى

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}
}

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);
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top