Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/63.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 正则表达式匹配rails获取索引URL_Ruby On Rails_Ruby_Regex - Fatal编程技术网

Ruby on rails 正则表达式匹配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/

我正在尝试创建一个正则表达式,以便只匹配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/')
#=> 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
    -字符串的开头
  • http:\/\/localhost:3000\/v2\/制造商
    -a
    http://localhost:3000/v2/manufacturers
    string
  • (?:\/?(?:\?\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+)?$