Problem with regular expression

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
definewebsites
Forum Newbie
Posts: 19
Joined: Thu May 01, 2008 9:51 pm

Problem with regular expression

Post 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... :(
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Problem with regular expression

Post by GeertDD »

Before giving any regex advice, wouldn't it be easier to just explode() the text on "/"?
definewebsites
Forum Newbie
Posts: 19
Joined: Thu May 01, 2008 9:51 pm

Re: Problem with regular expression

Post 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.
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

Re: Problem with regular expression

Post 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>[^/]+)}
definewebsites
Forum Newbie
Posts: 19
Joined: Thu May 01, 2008 9:51 pm

Re: Problem with regular expression

Post 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
User avatar
GeertDD
Forum Contributor
Posts: 274
Joined: Sun Oct 22, 2006 1:47 am
Location: Belgium

#

Post 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:
{/}
#/#
~/~
...
Post Reply