-1

I have an input string like below:

"/myWS/api/Application/IsCarAvailable/123456/2017"

It is the end of a Web API call that I am making. I need to easily extract the 123456 from the URL.

I was hoping something like the below would work

       string[] numbers = Regex.Split(input, @"\D+");

However, when I set a breakpoint on numbers and run the code it is showing an array of 3 elements?

Element at [0] is ""
Element at [1] is 123456
Element at [2] is 2017

Does anyone see why it would be getting the empty string as the first element?

Ctrl_Alt_Defeat
  • 3,933
  • 12
  • 66
  • 116

3 Answers3

5

I suggest matching, not splitting:

   string source = @"/myWS/api/Application/IsCarAvailable/123456/2017";

   string[] numbers = Regex 
     .Matches(source, "[0-9]+") 
     .OfType<Match>()
     .Select(match => match.Value)
     .ToArray();

Please, notice that \d+ in .Net means any unicode digits (e.g. Persian ones: ۰۱۲۳۴۵۶۷۸۹): that's why I put [0-9]+ pattern (RegexOptions.ECMAScript is an alternative if \d+ pattern is preferrable).

Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

If your string is always in the same format, this would work:

string numbers = input.Split('/')[input.Split('/').Length - 2];
Icculus018
  • 1,018
  • 11
  • 19
0

I think this is because the split method "splits" the string at the matching expression. So the empty string is the part before the first match. Any reason why you would not use Regex.Matches(input,"\\d+") instead?

        string numtest = "http://www.google.com/test/123456/7890";
        var matchResult = Regex.Matches(numtest, "\\d+");
        for (int i = 0; i < matchResult.Count; i++)
            Console.WriteLine($"Element {i} is {matchResult[i].Value}");

Hope that helps. Regards!

K. Berger
  • 361
  • 1
  • 9