c# substring indexof

refer picture refer · May 3, 2011 · Viewed 39.5k times · Source

i have a string which looks like this - "FirstName||Sam LastName||Jones Address||123 Main ST ..." (100 more different values)

I want to find only Sam and Jones from the entire string.

so string firstname = originalstring.substring ... etc.

Does anyone know how I can do this?

ADDITION - I think i forgot to mention couple of things.

FirstName||Sam\r\n MiddleName||\r\n LastName||Jones\r\n ....

So now if i count the number of characters that wont help me, cause could need more items other than just firstname and lastname.

Answer

Aliostad picture Aliostad · May 3, 2011

Use Regular expressions:

string myString = "FirstName||Sam LastName||Jones Address||123 Main ST...";
string pattern = @"FirstName\|\|(\w+) LastName\|\|(\w+) ";
Match m = Regex.Match(myString, pattern);
string firstName = m.Groups[1].Value
string lastName = m.Groups[2].Value;

See its Demo here.