Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to substring from a string using c#?

Tags:

substring

c#

.net

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?

like image 500
Jango Avatar asked Feb 22 '10 18:02

Jango


2 Answers

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
like image 124
Michael Stum Avatar answered Nov 15 '22 09:11

Michael Stum


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.

like image 21
Oded Avatar answered Nov 15 '22 07:11

Oded