What is the best way to analyze this number of the longest string in C #?

advertisements

I have the following example strings

"CTS3010 - 6ppl"

or

"CTs3200 - 14ppl"

or

 "CTS-500 2ppl"

and i need to parse out the number from these strings. What is the best way to parse out the number before the "ppl" at the end of the string. Do i need regex? I have logic to loop backward but it feels like there is a more elegant solution here.

These are just examples but all examples seem to follow the same pattern being

  • A bunch of text
  • A number
  • ppl suffix

You can do this to grab the number right before "ppl":

using System.Text.RegularExpressions;
...

Regex regex = new Regex("([0-9]+)ppl");
string matchedValue = regex.Match("CTS-500 122ppl").Groups[1].Value;

In this case matchedValue will be 122.

If you want to be safe, and you know "ppl" will always be at the end of the string, I would change the Regex to: "([0-9]+)ppl$" (the only difference is the dollar sign at the end).