I'm matching urls, so I can connect requests to controllers/views, and there are multiple options for a few of the urls, only one of which can have anything following it in the url, but I also need to have what comes after available as a named group.
Examples:
- /admin/something #match
- /admin/something/new #match
- /admin/something/new/id #fail
- /admin/something/edit #fail
- /admin/something/edit/id #match
There are many other possibilities, but thats good enough for an example. Basically, if the url ends in 'new', nothing can follow, while if it ends in 'edit' it also must have an id to edit.
The regex I've been using so far:
^/admin/something(?:/(?P<action>new|edit(?:/(?P<id>\d{1,5}))))?$
A whitespace-exploded version:
^/admin/something(?:/
(?P<action>
new| # create a new something
edit(?:/ # edit an old something
(?P<id>\d{1,5}) # id to edit
)
)
)? # actions on something are optional
$
But then if the url is '/admin/something/edit/id' the 'action' group is 'edit/id'. I've been using a little bit of string manip within the controller to cut down the action to just... the action, but I feel like a positive lookahead would be much cleaner. I just haven't been able to get that to work.
The lookahead regex I've been working at: (will match 'new', but not 'edit' [with or without an id])
^/admin/something(?:/(?P<action>new|edit(?=(?:/(?P<id>\d{1,5})))))?$
Any tips/suggestions would be much appreciated.