Marston Gould
Marston Gould

Reputation: 36

match regex with state, but not city (or vice versa)

I have a series of URLs in this format

/category/state/city

I'd like to match

/category/state

but not

/category/state/city

I've tried using a lookahead to eliminate situations where there are 3 forward slashes, but I must be doing something wrong.

Upvotes: 0

Views: 80

Answers (2)

Bohemian
Bohemian

Reputation: 425033

For the whole URL:

^http://(/[^/]+){2}$

For just the path:

^(/[^/]+){2}$

Upvotes: 1

KernelPanic
KernelPanic

Reputation: 600

^\/[^\/]*\/[^\/]*$ matches:

^             start of string
\/            exactly 1 /
[^\/]*        0 or more non-/ characters ("category")
\/            exactly 1 /
[^\/]*        0 or more non-/ characters ("state")
$             end of string

You can of course modify [^\/]* to more precisely limit what counts as a state or category (for instance [^\/]+ doesn't allow the empty string, and \w* only allows word characters).

Upvotes: 0

Related Questions