Ruby on rails 正则表达式匹配rails获取索引URL
我正在尝试创建一个正则表达式,以便只匹配rails中的索引URL(带或不带参数) 以下三点符合我的预期:Ruby on rails 正则表达式匹配rails获取索引URL,ruby-on-rails,ruby,regex,Ruby On Rails,Ruby,Regex,我正在尝试创建一个正则表达式,以便只匹配rails中的索引URL(带或不带参数) 以下三点符合我的预期: regex = /^http:\/\/localhost:3000\/v2\/manufacturers\/?(\S+)?$/ regex.match?('http://localhost:3000/v2/manufacturers?enabled=true') #=> true regex.match?('http://localhost:3000/v2/manufacturers/
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,您可以使用
/\Ahttp:\/\/localhost:3000\/v2\/manufacturers(?:\/?(?:\?\S+)?|\/1\/models\/?)?\z/
见
图案细节
-字符串的开头\A
-ahttp:\/\/localhost:3000\/v2\/制造商
stringhttp://localhost:3000/v2/manufacturers
-以下可选序列:(?:\/?(?:\?\S+)\/1\/型号)
-可选的\/?
字符/
-可选的(?:\?\S+)
和1+非空白序列?
-或|
-\/1\/models\/?
字符串和末尾的可选/1/models
/
-字符串结尾\z
\/?(\S+)?$/
致:
这将创建一个可选的非捕获组(?:\?\S+\d+\/\S+)
- 为问号和非空白字符匹配
\?\S+
- 或
|
- 为添加的
1/型号
字符使字符成为可选字符 这对我很有用:
http:\/\/localhost:3000\/v2\/manufacturers?\/?
r=/http://localhost:3000/v2/manufacturers?/?$/
r、 匹配(“”)
=>零
r、 匹配(“”)
=>零
您的问题是什么?@WiktorStribiżew done,谢谢如果匹配了
/?
,则非捕获组可能会更改为。或者OP可以使用.+1进行解释和拨弄。我添加了另一个有效的案例,如果你能涵盖,我将接受答案@WiktorStribiżew@fabriciofreitag我编辑了答案以解决所有新的测试用例。顺便说一句,在RoR中,您应该使用\A
和\z
锚,而不是^
和$
来匹配字符串的开头和结尾。这是一种更好的方法。被@WiktorStribiżew无故否决。©版权所有。
\/?(?:\?\S+|\d+\/\S+)?$