Artanis
Artanis

Reputation: 1005

Regex - match URL, but not deeper levels

I'm updating site where I have little control over the content structure or engine, so I must conditionally render a widget depending on URL match.

I need my code to execute when Regex match

www.example.com/index.php/category

but NOT when it matches

www.example.com/index.php/category/subcategory

I've made this far by far: www\.example\.[^.]+/category, but unfortunatly this also matches both aformentioned cases, while I need it to match only a second one. Can you please suggest, how to stop Regex at first /category, instead of matching further URLs?

Upvotes: 0

Views: 276

Answers (3)

Emma
Emma

Reputation: 27723

My guess is that this expression might likely work:

^(?:https?:\/\/)?(?:www\.)?[^.]+\.[^\/]+\/[^\/]+\/[^\/]+(?:\/)?$

We can also explicitly define the example.com:

^(?:https?:\/\/)?(?:www\.)?example\.com\/[^\/]+\/[^\/]+(?:\/)?$

DEMO

The expression is explained on the top right panel of regex101.com, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs, if you like.

RegEx Circuit

jex.im visualizes regular expressions:

enter image description here

Upvotes: 1

Rakib
Rakib

Reputation: 145

You can use the follow pattern to match your Url string upto category

^www.example.com\/\S+\/category$

You can check here for further explanation and experiment on how it works.

Upvotes: 1

CinCout
CinCout

Reputation: 9619

Your regex won't match any of the cases since you are looking for characters except . in between www.example. and /category but clearly index.php has a . in it.

Use the following instead:

www\.example\.\S+\/category$

Here I am anchoring the end of the search string via $, and looking for at least one non-whitespace character in between www.example. and /category.

Demo

Upvotes: 1

Related Questions