27

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,302
  • 5
  • 32
  • 50

1 Answers1

32

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
  • 35,754
  • 6
  • 94
  • 129