tags:

views:

32

answers:

2

I have a user specified URL that has a wildcard in it, e.g. http://site.com/project/*/account

In this case * could be anything, a number, a character or anything else.

I want to get regex that would find a match for that. The location of the wildcard * changes and could be http://site.com/user/*/title or http://site.com/user/*/*/*/delete (just as an example, depends on the site ... so all possibilities should be supported)

Any ideas or suggestions on how to do this? I was thinking of just getting the regex code for any character and replacing all occurrence of * with that regex code. Then comparing that with the current URL to see if it is a match.

A: 

You can use a URITemplate to do that matching.

Instead of this

http://site.com/user/*/title

You have to do this

http://site.com/user/{userId}/title

You should be able to find a C# version of it or be able to build it yourself, refering the java code

Here's a link to java source

But if you are looking to match the * instead of using the URI template, replace all the occurances of '*' with '(.*)' and create a regexp with that newly replaced URI. Then just do a regexp test or match

naikus
+1  A: 

I think your idea should work.

It is the same way globs are implemented in the Python standard library. The glob is translated into an equivalent regular expression with the * and ? wildcards translated into .* and .. In your case you would replace * with something like [^/]+.

The only problem with this approach is that you'd have to escape all the regex control characters so . needs to be replaced with \. and [ with \[ and so on.

hwiechers
Good point about escaping the regex characters.
rksprst