我正在尝试创建一个regex,以便只匹配rails中的索引urls (有或没有参数)。
以下三个与我所期望的相匹配:
regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/
regex.match?('http://localhost:3000/v2/manufacturers?enabled=true')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers')
#=> true我希望正则表达式与这些不匹配:
regex.match?('http://localhost:3000/v2/manufacturers/1')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/123')
#=> true
regex.match?('http://localhost:3000/v2/manufacturers/1?enabled=true')
#=> true编辑:
我很抱歉,但我忘了说它应该是匹配的:
regex.match?('http://localhost:3000/v2/manufacturers/1/models')因为它是一个有效的索引url。
发布于 2017-12-04 11:06:44
你可以用
/\Ahttp:\/\/localhost:3000\/v2\/manufacturers(?:\/?(?:\?\S+)?|\/1\/models\/?)?\z/见Rubular演示
模式细节
\A -字符串的开始http:\/\/localhost:3000\/v2\/manufacturers -一个http://localhost:3000/v2/manufacturers字符串(?:\/?(?:\?\S+)?|\/1\/models)? -一个可选的序列:\/? -一个可选的/字符(?:\?\S+)? - ?和1+非空格的可选序列| -或\/1\/models\/? - /1/models字符串和末尾的可选/
\z -字符串的末端。https://stackoverflow.com/questions/47631890
复制相似问题