Doublespeed Doublespeed - 1 month ago 6
Ruby Question

Identify extract & replace part of a string in ruby

I've been having difficulty trying to figureout how to go about solving this issue. I have 2 kinds of URLs in which I need to be able to update/increment the number value for the page.

Url 1:

forum-351-page-2.html


In the above, I would like to modify this url for n pages. So I'd like to generate new urls with a given range of say page-1 to page-30. But that's all I'd like to change. page-n.html

Url 2:

href="forumdisplay.php?fid=115&page=3


The second url is different but I feal it's easier visit.

Answer
R = /
    (?:             # begin non-capture group
      (?<=-page-)   # match string in a positive lookbehind
      \d+           # match 1 or more digits
      (?=\.html)    # match period followed by 'html' in a positive lookahead
    )               # close non-capture group
    |               # or
    (?:             # begin non-capture group
      (?<=&page=)   # match string in a positive lookbehind
      \d+           # match 1 or more digits
      \z            # match end of string
    )               # close non-capture group
    /x              # free-spacing regex definition mode

def update(str, val)
  str.sub(R, val.to_s)
end

update("forum-351-page-2.html", 4)
  #=> "forum-351-page-4.html"
update("forumdisplay.php?fid=115&page=3", "4")
  #=> "forumdisplay.php?fid=115&page=4"