REGEX - how to match exacly 3 words from url?

Viewed 64

I would like to match with regex exacly 3 words from search phrase from url but not match 4 or more. URL can have some variations. The problem is shown as below. Regex should match and not match following examples:

SHOULD MATCH:
https://example.com/search=any%20url%20encoded_word-here
https://example.com/search=any%20url%20encoded_word-here%20
https://example.com/search=z%C5%82oty%20z%C5%82oty%20z%C5%82oty
https://example.com/search=z%C5%82oty%20z%C5%82ota%20%C5%82ata
https://example.com/search=any%20%20word%20%20here
https://example.com/search=any%20word%20here&color=blue
https://example.com/search=any-1st%20word_2nd%20here3

SHOULD NOT MATCH:
https://example.com/search=one%20two%20three%20four
https://example.com/search=one%20%20two%20%20three%20%20four
https://example.com/search=one%20%20two%20three%20%20four
https://example.com/search=one%20%20two%20%20three%20%20four
https://example.com/search=one%20two%20three%20four&color=blue
https://example.com/search=z%C5%82oty%20z%C5%82oty%20z%C5%82oty%20word

Started here https://regex101.com/r/0qzCJV/1 but I have no idea how to not match on conditions. Can you pls help me guys?

2 Answers

You may use this regex with a negative lookahead to fail the match when there are 3 %20 followed by at least 1 more character:

^(?!(?:.+?%20){3}.)(?:.+?%20){2}.+?(?:%20)?$

RegEx Demo

RegEx Details:

  • ^: Start
  • (?!(?:.+?%20){3}.): Negative lookahead to fail the match when we have 3 occurrences of %20 followed by at least 1 character
  • (?:.+?%20){2}: Match 1+ of any characters followed by %20. Repeat this match 2 times to match 2 words
  • .+?: Match 1+ of any characters
  • (?:%20)?: Match optional %20 before end
  • $: End

Or use possessive quantifier to reduce backtracking:

^(?!(?:.+?%20){3}+.)(?:.+?%20){2}.+?(?:%20)?$

Try this:

^(((?!%20).)*(%20)+){2}((?!%20).)*(%20)?$

See live demo.

This uses a negative look ahead to match up to %20, then any number of %20, and all that twice. Then finish with anything not %20, except there may be %20 at the end.


Note: Your examples non-matches did not include urls with less than 3, eg

https://example.com/search=one%20two

Related