Page 1 of 1

Problem with regular expression

Posted: Mon Oct 27, 2008 6:48 am
by definewebsites
Hi there,

I've had a problem for the past couple days trying to create a match for some urls that I want to use..

For example in trying to match

Code: Select all

 
localhost/place/britain
 
I used the following:

Code: Select all

 
{^place\/(?P<country>\w+|\w+[[:punct:]]+\w+)$}
 
It works fine and I am able to capture the "country" variable which in this case is britain, however when I make the url,

Code: Select all

 
localhost/place/britain/london
 
The regular expression captures "britain/london" as the "country" variable which is not what I want it to do. I expect that it would tell me that no match was found.

Is there something I am doing wrong... :(

Re: Problem with regular expression

Posted: Mon Oct 27, 2008 12:25 pm
by GeertDD
Before giving any regex advice, wouldn't it be easier to just explode() the text on "/"?

Re: Problem with regular expression

Posted: Mon Oct 27, 2008 12:30 pm
by definewebsites
That is true though, never thought about that..It would save me having to use regular expressions for matching..However, I did find a solution to my problem by making the pattern match anything except the "/", as below,

Code: Select all

 
{^place\/(?P<country>[^\/]+)}
 
Thanks for the idea though, that is an interesting alternative.

Re: Problem with regular expression

Posted: Mon Oct 27, 2008 1:52 pm
by GeertDD
I see. Note though that "/" is not a special regex character, so you shouldn't escape it. Your regex becomes a bit more readable at the same time:

Code: Select all

{^place/(?P<country>[^/]+)}

Re: Problem with regular expression

Posted: Mon Oct 27, 2008 5:35 pm
by definewebsites
Thanks for the tip. I did read somewhere that it needed to be escaped...hmm...Guess it must have been the wrong information..Thanks for the correction

#

Posted: Tue Oct 28, 2008 2:10 am
by GeertDD
You only need to escape "/" if you are using it as a delimiter as well, but that is not the case in your regex.

Code: Select all

Espace needed:
/\//
 
Don't escape:
{/}
#/#
~/~
...