1

I am trying to come up with a regular expression that matches the following URLs:

http://test.com/bobs/your/uncle/1
http://test.com/bobs/your/uncle/5
http://test.com/bobs/your/uncle/5?tab=1

But does not match the following URLs:

http://test.com/bobs/your/uncle/1/brah/5
http://test.com/bobs/your/uncle/1/brah/5?tab=2

I tried the following regex

/bobs/your/uncle/\d+\??

Which works for the first three URLs above, but not the last two.

2 Answers 2

4

You can use this regex:

/bobs/your/uncle/\d+(?:\?|$)

(?:\?|$) will match ? or end of input after your desired input URIs.

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

Comments

3

You need to use start and end anchors :

'bobs/your/uncle/\d+\??[^/]*$'

See demo https://regex101.com/r/pP2fL1/1

you can use [^/]* to match some extra strings like tab=1 which match any thing except /.

1 Comment

Should have been a bit clearer in my question, but I actually wanted to ignore the domain as well, since I'm working with localhost as well as the online staging environment. So match both http://test.com/bobs/your/uncle/1 and http://localhost:8080/bobs/your/uncle/1. But I wasn't clear in my question, so I'm still giving you an upvote since it works if I remove the the start anchor and the domain.

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.