【问题标题】:replace specific text in ruby using regex使用正则表达式替换 ruby​​ 中的特定文本
【发布时间】:2017-07-12 00:31:53
【问题描述】:

在 ruby​​ 中,我正在尝试用新数字替换以下网址的 粗体 部分:

/ShowForum-g1-i12105-o20-TripAdvisor_Support.html

我将如何定位和替换 -o20- 使用 -o30- 或 -o40- 或 -o1200- ,同时保留 URL 的其余部分 完好无损的? url 可以是任何东西,但我希望能够找到这个确切的 -o20- 模式并将其替换为我想要的任何数字。

提前谢谢你。

【问题讨论】:

    标签: ruby regex rubular


    【解决方案1】:

    希望这会奏效。

    url = "/ShowForum-g1-i12105-o20-TripAdvisor_Support.html"
    url = url.gsub!(/-o20-/, "something_to_replace") 
    puts "url is : #{url}"
    

    输出:

    sh-4.3$ ruby main.rb                                                                                                                                                 
    url is : /ShowForum-g1-i12105something_to_replaceTripAdvisor_Support.html 
    

    【讨论】:

    • 这给了我一个错误:语法错误,意外的 tIDENTIFIER,期待 ')' secondUrl.gsub(/\-o20\-/,'-o90-') ^
    【解决方案2】:
    url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
    

    上面的 sn-p 会将数字替换为 (本身 + 10)。

    url = '/ShowForum-g1-i12105-o20-TripAdvisor_Support.html'
    
    url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
    #⇒ "30"
    url
    #⇒ "/ShowForum-g1-i12105-o30-TripAdvisor_Support.html"
    url[/(?<=-o)\d+(?=-)/] = ($&.to_i + 10).to_s
    #⇒ "40"
    url
    #⇒ "/ShowForum-g1-i12105-o40-TripAdvisor_Support.html"
    

    用你想要的任何数字替换:

    url[/(?<=-o)\d+(?=-)/] = "500"
    url
    #⇒ "/ShowForum-g1-i12105-o500-TripAdvisor_Support.html"
    

    更多信息:String#[]=

    【讨论】:

    • Mudsie,我对这个问题的理解是"-o20" 是一个给定的字符串,这当然大大简化了这个问题。
    • @CarySwoveland 我读过“我的目标是用 -o30- 或 -o40- 或 -o1200- 替换 -o20-”,因为目标是更新数字,所以我尽我所能让它变得简单:)
    猜你喜欢
    • 2016-08-02
    • 2011-09-05
    • 2017-10-18
    • 2018-03-16
    • 1970-01-01
    • 2014-03-11
    • 2015-07-25
    相关资源
    最近更新 更多