-1

I need to have the ability to parse out a series of numbers in a string in C# / Regex. The numbers can be one or more digits long and are always at the end of the string and after the word "ID" for example:

"Test 123 Test - ID 589"

In this case I need to be able to pick out 589.

Any suggestions? Some of the code That I have used picks out all the numbers which is not what I want to do.

Thanks

R M
  • 119
  • 1
  • 4
  • 9

4 Answers4

3

I would use the pattern @"ID (\d+)$"

using System.Text.RegularExpressions;
var s = "Test 123 Test - ID 589";
var match = Regex.Match(s, @"ID (\d+)$");
int? id = null;
if (match.Success) {
  id = int.Parse(match.Groups[1].Value);    
}
James Kyburz
  • 13,775
  • 1
  • 32
  • 33
1
string resultString = null;
try {
    Regex regexObj = new Regex(@"ID (?<digit>\d+)$");
    resultString = regexObj.Match(subjectString).Groups["digit"].Value;
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Dariusz
  • 15,573
  • 9
  • 52
  • 68
1

foo.Substring(foo.IndexOf("ID")+3)

Asdfg
  • 11,362
  • 24
  • 98
  • 175
0

This is the most specific pattern, in case not every line ends with a number you're interested in:

@"\bID\s+(\d+)$"

Note: Target numbers will be in capture group 1.

However, based on your description, you could just use this:

@"\d+$"

It simply looks for a string of numeric digits at the very end of each line. This is what I'd go with.

Justin Morgan - On strike
  • 30,035
  • 12
  • 80
  • 104