0

I'm going to have 2 different sets of URLS

/marketplace/producer/123-producer-name
/marketplace/producer/123-producer-name/5-genre/500-max-price/0-added/newest/1-page

I know the regular expression for the second, but for the first one i'm finding it tricky. I'm trying to match the expression, but I want to make sure it doesn't match the second one as well. I'm using the following;

/\/marketplace\/producer\/([0-9]+)\-[^\/]/

My logic at the end being match every character except a forward slash, which would then mean it's s possible match for the second one. But when I test it, it returns true even with a forward slash. What am I doing wrong?

3
  • I'd recommend using something like a hash at the start and end of your regexp so it's easier to read: #\/mark....-[^\/]# Commented Feb 14, 2013 at 8:45
  • @Seer Wouldn't you mean #/mark....\-[^/]# as the modifier was changed (hence you wouldn't have to escape slashes?) Commented Feb 14, 2013 at 8:47
  • @h2ooooooo My mistake, I do indeed! Commented Feb 14, 2013 at 9:07

2 Answers 2

3

Do it like this:

/^\/marketplace\/producer\/([0-9]+)-[^\/]+$/

Your regex searches for a string starting with a / followed by marketplace/producer/ followed by 1 or more digits followed by a - followed by one or more characters which is not a / and ends there.

I think the problem was with that there was no anchoring character and it matched a substring of the input also. Also you missed the + which makes the regex engine look for a single non-forwardslash character.

Sign up to request clarification or add additional context in comments.

5 Comments

Yeah i'm using that exact one and it returns true with and without a forward slash at the end
@Wasim You want to match /marketplace/producer/123-producer-name and don't match /marketplace/producer/123-producer-name/5-genre/500-max-price/0-added/newest/1-page, right?
Ah actually it does work. It returns true when the URL is /marketplace/producer/123-pro or /marketplace/producer/123-pro/ but returns false if anything comes after the last forward slash. This is exactly how I want it. Many thanks for your help
@Wasim Was it what you wanted?
@NaveedS yes I wanted to match /marketplace/producer/123-pro and /marketplace/producer/123-pro/ but nothing else unless it's /marketplace/producer/123-producer-name/5-genre/500-max-price/0-added/newest/1-‌​page
1

Simply use this regular expression [^/]+$. It will match everything after last forward slash.

Comments

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.