0

Given the following regular expression:

\/page1\/id\/(.*)\/type\/(.*)\/$

Which is to match the following URL path (and works):

/page1/id/331/type/test23/

How can I modify the regex to still match with the last slash missing, i.e:

/page1/id/331/type/test23

Thank you!

1 Answer 1

4

Just throw a question mark before the final slash to make it optional.

\/page1\/id\/\d+\/type\/[^\/]+\/?$

Also, you may want to make that ID non-greedy, or match numbers specifically (updated regex for you).

Sign up to request clarification or add additional context in comments.

8 Comments

Thank you for the quick reply. The problem I have with added a ? after the slash, it then matches anything after it (.e.g /page1/id/331/type/test23/3234/234/234/234/).
No. That's not the ?s fault. It's your greedy .*s in the middle, which I've removed for you. "Greedy" meaning it will consume as much as it can.
Absolutely brilliant! Thank you.
Isn't \d+ equally greedy? Obviously, you solve that by restricting to digits, but I don't see what that has to do with greediness?
One more question, how would I ignore any ?key=value strings at the end? (Would it be best to just strip them out before matching?)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.