1

I need a regex to match all URLs which does not contain specific URL parameter, for example if I make except=yes as an exception:

www.example.com  MATCH
www.example.com/  MATCH
www.example.com/?except=yes NOT MATCH
www.example.com/?test=true&except=yes NOT MATCH
www.example.com/?test=true&except=yes&foo=bar NOT MATCH
www.example.com/foo/bar/?except=yes NOT MATCH
www.example.com/?test=true&except=yesyes&foo=bar MATCH

The parameter should be exactly same but ignoring cases, I can achieve some points using negative look ahead but I cannot meet the requirement of last example.

Thanks in advance!

GreenVine
  • 15
  • 5

1 Answers1

3

Try this /^((?!except=yes).)*$/. Refer to this post for further details.

2.0.0-p648 :009 > regex = /^((?!except=yes).)*$/
 => /^((?!except=yes).)*$/ 
2.0.0-p648 :010 > "www.example.com".match regex
 => #<MatchData "www.example.com" 1:"m"> 
2.0.0-p648 :011 > "www.example.com/".match regex
 => #<MatchData "www.example.com/" 1:"/"> 
2.0.0-p648 :012 > "www.example.com/?except=yes".match regex
 => nil 
2.0.0-p648 :013 > "www.example.com/?test=true&except=yes".match regex
 => nil 
2.0.0-p648 :014 > "www.example.com/?test=true&except=yes&foo=bar".match regex
 => nil 
2.0.0-p648 :015 > "www.example.com/foo/bar/?except=yes".match regex
 => nil 
2.0.0-p648 :016 > "www.example.com/?test=true&except=yesyes&foo=bar".match regex
 => nil 

Edit

In order to match the last string(which contains except=yesyes), use the following regex. /^((?!except=yes\b).)*$/ The only difference is \b, which matches word boundary such as whitespace, punctuations.

> /^((?!except=yes\b).)*$/.match "www.example.com"
 => #<MatchData "www.example.com" 1:"m"> 
> /^((?!except=yes\b).)*$/.match "www.example.com/"
 => #<MatchData "www.example.com/" 1:"/"> 
> /^((?!except=yes\b).)*$/.match "www.example.com/?except=yes"
 => nil 
> /^((?!except=yes\b).)*$/.match "www.example.com/?test=true&except=yes"
 => nil 
> /^((?!except=yes\b).)*$/.match "www.example.com/?test=true&except=yes&foo=bar"
 => nil 
> /^((?!except=yes\b).)*$/.match "www.example.com/foo/bar/?except=yes"
 => nil 
> /^((?!except=yes\b).)*$/.match "www.example.com/?test=true&except=yesyes&foo=bar"
 => #<MatchData "www.example.com/?test=true&except=yesyes&foo=bar" 1:"r"> 
Community
  • 1
  • 1
Cheolho Jeon
  • 359
  • 1
  • 12
  • Thanks :) Sorry I made a mistake, the last example should be `MATCH` since _except_ not fully equals to _yes_ – GreenVine May 19 '16 at 04:12