tags:

views:

70

answers:

3

I have a string that looks like:

www.blah.com/asdf/asdf/asdfasedf/123

The string may have a slash followed by numbers, like /123 in the above example.

I want to extract the 123 from the string if it is present.

What would my regex be?

+3  A: 

You simply match a group of digits (\d+) and require the string to end after that

(\d+)$
naivists
+2  A: 

Terminate your regular expression with $ to signify the end of the line.

\/\d+$

To actually extract the number, use:

int number;
var match = Regex.Match(inputString,@"\/(\d+)$");
if(match != null)
    number = int.Parse(match.Groups[1].ToString());
Aviad P.
+3  A: 

This will match a slash followed by numbers at the end of a string and capture the numbers:

\/(\d*)$
mopoke
thanks, that is what I came up with also, but the slash seems to be part of the match?
mrblah
If you're saying that 'MAY be preceeded with a slash', then the slash shouldn't be a part of the regex!
naivists
In the example I gave, the slash is outside of the capturing parens, and so would not be part of the capture group. You can omit the leading slash if you don't care whether it's there or not. Your example had it preceded with a slash but if the slash is optional, just leave it out.
mopoke