1

I have two urls (below). I need to match the one that doesn't contain the "story" part in the it. I know i need to use negative lookhead/behind, but i cant for the life of me get it to work

Urls

news/tech/story/2014/oct/28/apple-iphone/261736

news/tech/2014/oct/28/apple-iphone/261736

Current Regex

news\/([a-z0-9-\/]{1,255})(\d{4})\/(\w{3})\/(\d{2})\/([a-z0-9\-]{1,50})\/(\d{1,10})

Example:

http://regex101.com/r/jC7jC4/1

3 Answers 3

1

you can try this one :

news\/(([a-z0-9-\/](?!story)){1,255})(\d{4})\/(\w{3})\/(\d{2})\/([a-z0-9\-]{1,50})\/(\d{1,10})
Sign up to request clarification or add additional context in comments.

Comments

1

You can use negative lookahead like this:

(?!.*\bstory\b)news\/([a-z0-9-\/]{1,255})(\d{4})\/(\w{3})\/(\d{2})\/([a-z0-9\-]{1,50})\/(\d{1,10})

RegEx Demo

(?!.*\bstory\b) is negative lookahead that will stop match if there is a word story in the URL.

Comments

1

You can check with strpos() if you don't have to use regex

 if (strpos($url, 'story') === false

1 Comment

Agreed. While negative assertions can do the job, the old saw about having two problems now applies especially well to situations like this, IMO. Future maintainers would thank you if you can pair the regex with some string operations that make the behaviour a little more clear.

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.