0

I'm trying to create a snippet of regex that will match a URL route.

Basically, if I have this route /users/:id I want /users/100 to match, but /users/100/edit not to match.

This is what I'm using now: users/(.*)/ but because of the greedy match it's matching regardless of what's after the user ID. I need some way of "breaking" the match if there's an /edit or something else on the end of the route.

I've looked into the Regex NOT operator but with no luck.

Any advice?

James Dawson
  • 5,309
  • 20
  • 72
  • 126

2 Answers2

1

Are you just trying to collect digits?

You could use users/(\d*)/

And this one is how you would do it if you wanted to collect everything until a /, and it uses a NOT, ^/users/[^/]*$

Kevin Johnson
  • 913
  • 7
  • 24
0

You can use negative lookahead:

users/(.*)/(?!edit)

This will always require a trailing slash however. Maybe a better solution would be:

users/(\d+)(?!/edit)

See this post for more information.

Community
  • 1
  • 1
JamesSwift
  • 863
  • 1
  • 7
  • 16