Curly brackets C # split issue

I have data in a string email

and id

in a format like below:

string s = "{email:ss@ss.com}{id:AB12345}";

      

I just want to remove the curly braces and extract the email and id from the above string into a variable as shown below.

string email = "ss@ss.com";
string id = "AB12345";

      

I've tried string.Format

other formatting as well. Since the email size and ID can vary, I cannot find a solution.

+3


source to share


5 answers


Usage can use Regex .

var match = Regex.Match("{email:ss@ss.com}{id:AB12345}", @"\{email:(.+)\}\{id:(.+)\}");
var email = match.Groups[1].Value;
var id = match.Groups[2].Value;

      



PS: The pattern (.+)

means the email and id are at least 1 character, otherwise the match won't find the email and id, if they can be empty you can change it to(.*)

+8


source


Using Split

, you can achieve it like this:



var parts = s.Split(new [] { '{', '}' }, StringSplitOptions.RemoveEmptyEntries);

string email = parts[0].Split(':')[1];
string id = parts[1].Split(':')[1];

      

+3


source


Regex would be a good solution, but since I'm not familiar with it, you can use methods Substring

and IndexOf

:

string s = "{email:ss@ss.com}{id:AB12345}";
string email = s.Substring(s.IndexOf(':') + 1, 
                           s.IndexOf('}') - s.IndexOf(':') - 1); // ss@ss.com
s = s.Substring(s.IndexOf('}') + 1);
string id = s.Substring(s.IndexOf(':') + 1, 
                        s.IndexOf('}') - s.IndexOf(':') - 1); // AB12345

      

Here . demonstration

0


source


string s = "{email:ss@ss.com}{id:AB12345}";
string[] str = s.Split("}{".ToArray());
string email = str[1].Replace("email:", "");
string id = str[3].Replace("id:", "");

      

0


source


  private static void Main(string[] args)
        {

            string s = "{email:ss@ss.com}{id:AB12345}";
            string email = string.Empty;
            string id = string.Empty;
            FillValue(s, out email, out id);
            Console.WriteLine("email:{0}\nid:{1}",email,id);
              Console.ReadKey();
        }

        private static void FillValue(string s, out string email, out string id)
        {
            var values = s.Replace("}{", "$").Replace("{",string.Empty).Replace("}",string.Empty).Split('$');
            email = values[0].Split(':')[1];
            id = values[1].Split(':')[1];
        }

      

0


source







All Articles