2

I have the following regular expression #^en/cities/(.*?)/$# and I want it to match anything, but stop at the first slash.

I.e. it should match 'paris' but not 'paris/france' if someone manages to type that URL.

I thought I already had it as non-greedy with the questionmark, but apparently not.

1 Answer 1

2

Use a negated character class.

#^en/cities/([^/]+)/$#

In your regex the non-greediness failed because you anchored the last slash to the end ($). Removing that would also make your regex work:

#^en/cities/.*?/#
Sign up to request clarification or add additional context in comments.

3 Comments

No need for the ? in your first example.
@ridgerunner - Hm, I think you might be mistaken. The delimeter here is # (in case that's what you missed) so the non-greedy quantifier must seek until a / is matched.
You are absolutely correct. I did miss the /. Comment retracted. Sorry bout that! +1

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.