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.
source to share
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(.*)
source to share
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
source to share
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];
}
source to share