31

in the following string:

/seattle/restaurant

I would like to match Seattle (if it is present) (sometimes the url might be /seattle/restaurant and sometimes it might be /restaurant). What I don't want is to match the following forward slash: seattle/

I have tried the following, but I cannot get it to work:

       /(.*[^/]?)restaurant(\?.*)?$

I need the first forward slash, so the solution is not to remove that, which I can do like this:

     (/?)(.*)/restaurant(\?.*)?$   

Thanks

Thomas

ThomasD
  • 2,464
  • 6
  • 40
  • 56

1 Answers1

37

What about something like this?

^/([^/]+)/?(.*)$

I tested it with python and seems to work fine:

>>> regex=re.compile(r'^/([^/]+)/?(.*)$')
>>> regex.match('/seattle').groups()
('seattle', '')
>>> regex.match('/seattle/restaurant').groups()
('seattle', 'restaurant')
jcollado
  • 39,419
  • 8
  • 102
  • 133