Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In C#, what is the best way to parse out this value from a string?

Tags:

string

c#

parsing

I have to parse out the system name from a larger string. The system name has a prefix of "ABC" and then a number. Some examples are:

ABC500
ABC1100
ABC1300

the full string where i need to parse out the system name from can look like any of the items below:

ABC1100 - 2ppl
ABC1300
ABC 1300
ABC-1300
Managers Associates Only (ABC1100 - 2ppl)

before I saw the last one, i had this code that worked pretty well:

string[] trimmedStrings = jobTitle.Split(new char[] { '-', '–' },StringSplitOptions.RemoveEmptyEntries)
                           .Select(s => s.Trim())
                           .ToArray();

return trimmedStrings[0];

but it fails on the last example where there is a bunch of other text before the ABC.

Can anyone suggest a more elegant and future proof way of parsing out the system name here?

like image 538
leora Avatar asked May 20 '13 13:05

leora


1 Answers

One way to do this:

string[] strings =
{
    "ABC1100 - 2ppl",
    "ABC1300",
    "ABC 1300",
    "ABC-1300",
    "Managers Associates Only (ABC1100 - 2ppl)"
};

var reg = new Regex(@"ABC[\s,-]?[0-9]+");

var systemNames = strings.Select(line => reg.Match(line).Value);

systemNames.ToList().ForEach(Console.WriteLine);

prints:

ABC1100
ABC1300
ABC 1300
ABC-1300
ABC1100

demo

like image 88
Ilya Ivanov Avatar answered Nov 09 '22 22:11

Ilya Ivanov