【问题标题】:Ruby regex returning unmodified string?Ruby正则表达式返回未修改的字符串?
【发布时间】:2021-10-13 16:37:54
【问题描述】:

对此很陌生,但我正在尝试使用 Ruby 和 Regex 进行重定向:

旧链接:https://blog.example.io/eng/2020/01/29/post-title

新的所需链接:https://example.io/blog/post-title

这是我正在使用的代码:

re = /https:\/\/blog\.(example\.io)(?:\/eng\/\d{4}\/\d{2}\/\d{2})?\/(.+)/
str = 'https://blog.example.io/eng/2018/02/21/post-title'
subst = 'https://$1/blog/$2'

result = str.gsub(re, subst)

但它正在返回:

https://blog.example.io/eng/2018/02/21/post-title

如何生成:“https://example.io/blog/post-title”?

编辑

使用我提供的修改后的正则表达式:

/https:\/\/blog\.(.*?)(?:\/eng\/\d{4}\/\d{2}\/\d{2})?\/(.+)/

我现在可以返回“https://$1/blog/$2”。 $1 和 $2 没有被“example.io”和“post-title”替换是否有原因?

【问题讨论】:

  • 你的正则表达式匹配blog.example.com,而不是blog.example.io
  • 很好@Barmar,我已经更新了这个问题,因为这是一个错字。
  • 您需要说明从一个字符串到另一个字符串的规则。例如,如果'blog.' 出现在任何位置,您是否希望删除它,如果它出现在'\\' 之后和/或'example.io' 之前,或者您是否希望删除'\\' 之后的任何以点结尾的字符串,例如'\\cat.',等等。
  • @pldfs :也许不相关,但我觉得在你的情况下,正则表达式是矫枉过正的。你可以简单地做一个result="https://example.io/blog/#{File.basename(str)}"

标签: regex ruby


【解决方案1】:

您的正则表达式模式似乎有点不对劲。考虑使用这个版本,它不对域和扩展做任何假设:

https:\/\/blog\.(.*?)(?:\/eng\/\d{4}\/\d{2}\/\d{2})?\/(.+)

然后,保持替换不变。 Check this demo 查看更新后的模式是否有效。

【讨论】:

  • 谢谢@Tim Biegeleisen。这会返回“http://$1/blog/$2”,所以我想我越来越近了。
【解决方案2】:

您的替换模式错误,正则表达式模式没有问题。

固定的 Ruby 代码是

re = /https:\/\/blog\.(example\.io)(?:\/eng\/\d{4}\/\d{2}\/\d{2})?\/(.+)/
str = 'h'+'ttps://blog.example.io/eng/2018/02/21/post-title'
subst = 'https://\1/blog/\2'
result = str.gsub(re, subst)
p result

请参阅online Ruby code

如果您需要匹配任何主机名,请使用

re = /https:\/\/blog\.([^\/]+)(?:\/eng\/\d{4}\/\d{2}\/\d{2})?\/(.+)/

【讨论】:

    猜你喜欢
    • 2015-02-07
    • 1970-01-01
    • 2018-07-23
    • 2013-11-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-29
    • 1970-01-01
    • 2016-05-04
    相关资源
    最近更新 更多