string format is always like this "FirstName=ABC;LastName=XZY;Username=User1;Password=1234".
I need the only UserName value (which is 'User1' in this case). I wanna achieve this in minimum line of code using substring method (or something else).
Help?
For the sake of completeness, here is the Regex way of doing it. This will also work if the order changes.
// using System.Text.RegularExpressions;
string test1 = "FirstName=ABC;LastName=XZY;Username=User1;Password=1234";
string test2 = "FirstName=ABC;LastName=XZY;Password=1234;Username=User1";
string test3 = "FirstName=ABC;LastName=XZY;Password=1234";
string regexPattern = @"(?<=Username=)[^;\n]*";
var userName1 = Regex.Match(test1, regexPattern).Value; // User1
var userName2 = Regex.Match(test2, regexPattern).Value; // User1
var userName3 = Regex.Match(test3, regexPattern).Value; // string.Empty
// Compiling can speed up the Regex, at the expense of longer initial Initialization
// Use when this is called often, but measure.
Regex compiledRx = new Regex(regexPattern,RegexOptions.Compiled);
var userNameCompiled1 = compiledRx.Match(test1).Value; // User1
var userNameCompiled2 = compiledRx.Match(test2).Value; // User1
var userNameCompiled3 = compiledRx.Match(test3).Value; // string.Empty
Looks like a delimited string, so this would work:
string result = myString.Split(';')[2].Split('=')[1];
However, if someone changes the value pair order, this will break.
There are better ways about this, that will not break if the order changes, the number of parameters is different etc - such as the Regular Expression as Michael posted, or the Linq queries posted by a number of people.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With