Niko
Niko

Reputation: 251

Regex match where part of string doesn't contain a character

I need a regexp that I want to match against several different strings.

The regex should retrieve a match for this string:

http://www.domain.com/category

But not for this:

http://www.domain.com/category/sports 

or

http://www.domain.com/category/sportsmanship

I have tried the following regex but it doesn't really want to work:

/categ.*?^((?!sports).)*$/g

Upvotes: 0

Views: 46

Answers (3)

Federico Piazza
Federico Piazza

Reputation: 31025

You can use this regex:

.*/category(?!/sports).*

Working demo

enter image description here

Upvotes: 2

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89629

You can write

/\/categ[^\/]*(?:\/(?!sports)[^\/]*)*$/

In this pattern, the negative lookahead checks after each slashes if the string "sports" doesn't follow.

Note: if you have to deal with long paths that contains the string "sports" relativly often, you can try this variant to speed up the pattern:

/\/categ(?=([^\/]*))\1(?:\/(?!sports)(?=([^\/]*))\2)*$/

Upvotes: 1

Avinash Raj
Avinash Raj

Reputation: 174826

I think you don't want to match the line which contains the string sports at the last. If yes then you could try the below regex,

^.*?categ(?:(?!sports).)*$

The problem with your regex is .*?^. ^ asserts that we are at the start of a line.

Upvotes: 0

Related Questions