我需要一个正则表达式来匹配所有不包含特定网址参数的网址,例如,如果我将 except = yes 作为例外:
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
参数应完全相同但忽略大小写,我可以使用负向前看来达到一些要点,但我不能满足上一个例子的要求。
提前致谢!
答案 0 :(得分:0)
试试这个/^((?!except=yes).)*$/
。有关详细信息,请参阅this post。
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
修改强>
为了匹配最后一个字符串(包含except=yesyes
),请使用以下正则表达式。 /^((?!except=yes\b).)*$/
唯一的区别是\b
,它匹配字边界,例如空格,标点符号。
> /^((?!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">