2

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
Yuck
  • 44,893
  • 13
  • 100
  • 132
leora
  • 163,579
  • 332
  • 834
  • 1,328

3 Answers3

6

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).

Adam Plocher
  • 13,142
  • 5
  • 42
  • 74
  • Is there any difference between `[0-9]` and `\d`? I see lots of people using `[0-9]` instead of `\d` these days... – Oscar Mederos Mar 02 '13 at 04:42
  • According to: http://stackoverflow.com/questions/273141/regex-for-numbers-only \d will match non-western numeric characters too. – Adam Plocher Mar 02 '13 at 04:46
1

Here's one way using LINQ:

const String ppl = "ppl";
var examples = new[] { "CTS3010 - 6ppl", "CTs3200 - 14ppl", "CTS-500 2ppl" };
var delimiters = new[] { " " };
var result = examples
    .Select(e => e.Split(delimiters, StringSplitOptions.RemoveEmptyEntries))
    .Select(t => t.Last().ToLowerInvariant().Replace(ppl, String.Empty))
    .Select(Int32.Parse)
    .ToList();

Note that this will fail if it can't parse the integer value. If you can't guarantee each string will end with NNppl you'll need to check that it is a numeric value first.

Yuck
  • 44,893
  • 13
  • 100
  • 132
0

I dunno about the "best way" but one method that is very easy to understand and modify is an extension method for a string object:

 public static int Parse(this string phrase)
    {
        if (string.IsNullOrWhiteSpace(phrase)) { throw new NullReferenceException("phrase is null");}

        string num = string.Empty;
        foreach (char c in phrase.Trim().ToCharArray()) {
            if (char.IsWhiteSpace(c)) { break; }
            if (char.IsDigit(c)) { num += c.ToString(); }
        }
        return int.Parse(num);
    }

Assumes " " is the break condition. You may prefer int.TryParse if there is some chance you don't get a number and/or maybe a System.Text.StringBuilder.

rism
  • 11,221
  • 14
  • 70
  • 110