【发布时间】: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)}"