【问题标题】:Regex to match rails get index urls正则表达式匹配 rails 获取索引 url
【发布时间】:2017-12-04 11:03:55
【问题描述】:

我正在尝试创建一个正则表达式以仅匹配 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

【问题讨论】:

  • 你有什么问题?
  • @WiktorStribiżew 完成,谢谢

标签: ruby-on-rails ruby regex


【解决方案1】:

你可以使用

/\Ahttp:\/\/localhost:3000\/v2\/manufacturers(?:\/?(?:\?\S+)?|\/1\/models\/?)?\z/

Rubular demo

模式详情

  • \A - 字符串开头
  • http:\/\/localhost:3000\/v2\/manufacturers - http://localhost:3000/v2/manufacturers 字符串
  • (?:\/?(?:\?\S+)?|\/1\/models)? - 可选序列:
    • \/? - 一个可选的 / 字符
    • (?:\?\S+)? - ? 和 1+ 个非空格的可选序列
    • | - 或
    • \/1\/models\/? - /1/models 字符串和一个可选的 / 在末尾​​li>
  • \z - 字符串结束。

【讨论】:

  • 如果/?应该匹配,非捕获组可以更改为(?:\/|\/?\?\S+)?。或者 OP 可能会使用\Ahttp:\/\/localhost:3000\/v2\/manufacturers\/?(?:\?\S+)?\z
  • +1 用于解释和调整。我添加了另一个有效案例,如果您能说明我会接受答案。 @WiktorStribiżew
  • @fabriciofreitag 我编辑了答案以解决所有新的测试用例。顺便说一句,在 RoR 中,您应该使用 \A\z 锚而不是 ^$ 来匹配字符串的开头和结尾。
【解决方案2】:

您可以更改正则表达式的结尾:

\/?(\S+)?$/

到:

\/?(?:\?\S+|\d+\/\S+)?$

这将创建一个可选的非捕获组(?:\?\S+|\d+\/\S+)?

  • \?\S+ 匹配为您的问号和非空白字符
  • |
  • 匹配\d+\/\S+1/models添加的情况

Demo

【讨论】:

  • 更好的方法。
  • 被@WiktorStribiżew 无缘无故否决。 © 版权所有。
【解决方案3】:

? 字符使该字符可选

这对我有用:http:\/\/localhost:3000\/v2\/manufacturers?\/?

r = /http://localhost:3000/v2/manufacturers?/?$/

r.match('http://localhost:3000/v2/manufacturers/1?enabled=true') => 无

r.match('http://localhost:3000/v2/manufacturers/1') => 无

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    • 1970-01-01
    相关资源
    最近更新 更多