Search code examples
c#visual-studioparsingnumbersdata-extraction

Extract number from string value


I have a string that always come into this format:

"TM" + multiple Leading 0 + Number + Non-Number Character + Alphanumeric.

For example: TM000013452S20548, PB000013452S3DVSF.

How do I parse (in C# code) the varchar value to get the "Number" (13452) in this case?


Solution

  • You can use RegualarExpressions:

    (?:TM|PB)0{0,}(\d+)
    

    Like this:

    string input = "For example: TM000013452S20548, PB000013452S3DVSF.";
    var matches = Regex.Matches(input, @"(?:TM|PB)0{0,}(\d+)");
    foreach(Match m in matches)
        Console.WriteLine(int.Parse(m.Groups[1].Value));  
    

    Live Demo