【问题标题】:ruby regex: How to extract string from urlruby 正则表达式:如何从 url 中提取字符串
【发布时间】:2015-03-10 23:41:27
【问题描述】:

对rubular不太熟悉,想知道如何使用Ruby正则表达式从中提取“postreview-should-be-the-cause”

"{\"source_url\"=>\"http://testing.com/projects/postreview-should-be-the-cause\"}"

我得到的最好的是

check_user = url.split(/\b(\w+)\b/)
=> ["{\"", "source_url", "\"=>\"", "http", "://", "localhost", ":", "3000", "/", "projects", "/", "postreview", "-", "should", "-", "be", "-", "the", "-", "cause", "\"}"]

还在尝试各种方法。提前致谢。

【问题讨论】:

    标签: ruby regex rubular


    【解决方案1】:

    您可以使用string.scan 代替string.split

    > "{\"source_url\"=>\"http://testing.com/projects/postreview-should-be-the-cause\"}".scan(/(?<=\/)[^\/"]*(?=[^\/]*$)/)[0]
    => "postreview-should-be-the-cause"
    

    【讨论】:

    • 谢谢阿维纳什!哇,不知道扫描。到目前为止,string.scan 给了我这个输出。 check_user = url.scan(/\b(\w+)\b/) => [["source_url"], ["http"], ["localhost"], ["3000"], ["projects"], ["postreview"]、["should"]、["be"]、["the"]、["cause"]],如何将它们合并回"postreview-should-be-the-cause"?因为我需要稍后将其与另一个模型匹配。
    • 打印索引0,得到你想要的字符串。
    【解决方案2】:

    要从给定字符串中提取该子字符串,您可以使用以下匹配而不是拆分。

    result = url.match(/\w+(?:-\w+)+/)
    

    Working Demo

    【讨论】:

    • 我是新来的匹配,只是想知道这是否是使用匹配的正确方法? Model.find_by(puts 结果)
    • 我想我明白了,但请告诉我“Model.find_by(puts result)”是否有效。 =)
    【解决方案3】:
    \/(?!.*\/)
    

    由此拆分。得到第二个组件。查看演示。

    https://regex101.com/r/sH8aR8/48

    【讨论】:

      猜你喜欢
      • 2011-07-24
      • 1970-01-01
      • 1970-01-01
      • 2013-07-29
      • 2014-08-25
      • 1970-01-01
      • 2011-05-06
      • 1970-01-01
      相关资源
      最近更新 更多