Varun
Varun

Reputation: 5

I am not able to fix a greedy regular expression

I need to capture from the beginning of the url to the first instance of the /blog in the example url

https://subdomain.website.com/groups/aa-var-group-members-only-two/blog/2017/10/22/blog-post-3

the regular expression i have right now is (.*)/blog

is greedy and captures till the the last instance of "/blog" i.e

https://subdomain.website.com/groups/aa-var-group-members-only-two/blog/2017/10/22/blog

while my expected result is

https://subdomain.website.com/groups/aa-var-group-members-only-two/blog

can someone help me fix the regular expression

Upvotes: 0

Views: 61

Answers (1)

oetoni
oetoni

Reputation: 3867

in your example, this

^(.*?)blog

That will capture all until the first blog mention

enter image description here

and you can play with it here https://regex101.com/r/nYmOeh/1 :)

.*? is the non greedy version of your initial example. Sidyll here gave a perfect explanation on greedy vs non-greedy.

alternatively, capturing all (without blog):

/.+?(?=blog)/

enter image description here

Upvotes: 1

Related Questions