tags:

views:

237

answers:

4

In C#, how would I capture the integer value in the URL like:

/someBlah/a/3434/b/232/999.aspx

I need to get the 999 value from the above url. The url HAS to have the /someBlah/ in it. All other values like a/3434/b/232/ can be any character/number.

Do I have escape for the '/' ?

+4  A: 

Try the following

var match = Regex.Match(url,"^http://.*someblah.*\/(\w+).aspx$");
if ( match.Success ) {
  string name = match.Groups[1].Value;
}

You didn't specify what names could appear in front of the ASPX file. I took the simple approach of using the \w regex character which matches letters and digits. You can modify it as necessary to include other items.

JaredPar
A: 
^(?:.+/)*(?:.+)?/someBlah/(?:.+/)*(.+)\.aspx$

This is a bit exhaustive, but it can handle scenarios where /someBlah/ does not have to be at the beginning of the string.

The ?: operator implies a non-capturing group, which may or may not be supported by your RegEx flavor.

David Andres
+3  A: 

You are effectively getting the file name without an extension.

Although you specifically asked for a regular expression, unless you are in a scenario where you really need to use one, I'd recommend that you use System.IO.Path.GetFileNameWithoutExtension:


Path.GetFileNameWithoutExtension(Context.Request.FilePath)
Alfred Myers
but it has to match a given pattern, I don't want to modify all urls.
mrblah
**My solution does not require you to modify any URLs.** All it does is return you the file name regardless of matching a regular expression or not. If you need to further have the file match a regular expression, then you can appy the filter just to the file name instead of the entire URL.
Alfred Myers
A: 
Regex regex = new Regex("^http://.*someBlah.*/(\\d+).aspx$");
Match match = regex.Match(url);
int result;
if (match.Success)
{
   int.TryParse(match.Groups[1].Value, out result);
}

Using \d rather than \w ensures that you only match digits, and unless the ignore case flag is set the capitalisation of someBlah must be correct.

jat45