【问题标题】:Regex to extract last number portion of varying URL正则表达式提取不同 URL 的最后一个数字部分
【发布时间】:2017-05-27 17:12:00
【问题描述】:

我正在创建一个 URL 解析器并拥有三种 URL,我想从中提取 URL 末尾的数字部分,并将提取的数字增加 10 并更新 URL。我正在尝试使用正则表达式进行提取,但我是正则表达式的新手并且遇到了麻烦。

这是三个 URL 结构,我想增加它们的最后一个数字部分:

  1. 将最后一个数字 20 增加 10:

    http://forums.scamadviser.com/site-feedback-issues-feature-requests/20/
    
  2. 将最后一个数字 50 增加 10:

    https://forums.questionablecontent.net/index.php/board,1.50.html
    
  3. 将最后一个数字 30 增加 10:

    https://forums.comodo.com/how-can-i-help-comodo-please-we-need-you-b39.30/
    

【问题讨论】:

  • 为什么要再造一个轮子?在 Ruby 的 URI 和 Addressable::URI 之间有很多经过良好测试的代码。
  • 我们希望看到您尝试解决这个问题,而不是为您编写与您的尝试无关的代码。

标签: ruby regex rubular


【解决方案1】:

像这样:

urls = ['http://forums.scamadviser.com/site-feedback-issues-feature-requests/20/', 'https://forums.questionablecontent.net/index.php/board,1.50.html', 'https://forums.comodo.com/how-can-i-help-comodo-please-we-need-you-b39.30/']
pattern = /(\d+)(?=[^\d]+$)/

urls.each do |url|
    url.gsub!(pattern) {|m|  m.to_i + 10}
end

puts urls

你也可以在这里在线测试:https://ideone.com/smBJCQ

【讨论】:

    【解决方案2】:

    此正则表达式仅匹配每个 URL 中的最后一个整数,方法是使用前瞻(“看到”模式但不吃任何字符):

    \d+(?=\D*$)
    

    online demo 在这里。

    【讨论】:

      【解决方案3】:

      使用\d+(?!.*\d) 正则表达式,您将获得字符串中的最后一个数字块。然后,用s.gsub加块修改数字,放回结果。

      this Ruby demo:

      strs = ['http://forums.scamadviser.com/site-feedback-issues-feature-requests/20/', 'https://forums.questionablecontent.net/index.php/board,1.50.html', 'https://forums.comodo.com/how-can-i-help-comodo-please-we-need-you-b39.30/']
      arr = strs.map {|item| item.gsub(/\d+(?!.*\d)/) {$~[0].to_i+10}}
      

      注意:$~ 是一个 MatchData 对象,使用[0] 索引我们可以访问整个匹配值。

      结果:

      http://forums.scamadviser.com/site-feedback-issues-feature-requests/30/
      https://forums.questionablecontent.net/index.php/board,1.60.html
      https://forums.comodo.com/how-can-i-help-comodo-please-we-need-you-b39.40/
      

      【讨论】:

      • 一个小更新:如果字符串可以有换行符,请使用/\d+(?!.*\d)/m(但我怀疑这里不是这种情况)。
      • 如果我想一次只做一个 url 而不是使用这张地图,我们该怎么做?
      • 上面的代码中已经有:item = item.gsub(/\d+(?!.*\d)/) {$~[0].to_i+10}
      【解决方案4】:

      试试这个正则表达式:

      \d+(?=(\/)|(.html))
      

      它将提取最后一个数字。

      演示:https://regex101.com/r/zqUQlF/1


      用这个正则表达式替换:

      (.*?)(\d+)((\/)|(.html))
      

      演示:https://regex101.com/r/zqUQlF/2

      【讨论】:

        猜你喜欢
        • 2018-08-18
        • 2020-01-17
        • 1970-01-01
        • 2011-07-02
        • 1970-01-01
        • 2021-09-10
        • 2016-08-05
        • 2013-02-10
        • 2018-11-04
        相关资源
        最近更新 更多