Get values between curly braces c#

前端 未结 3 1822
无人共我
无人共我 2020-12-11 04:27

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 be

相关标签:
3条回答
  • 2020-12-11 04:32

    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}
    }
    
    0 讨论(0)
  • 2020-12-11 04:41

    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);
    
    0 讨论(0)
  • 2020-12-11 04:44

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

    s.Split(new char[] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries)
    
    0 讨论(0)
提交回复
热议问题