0

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.

0

2 Answers 2

1
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"
Sign up to request clarification or add additional context in comments.

2 Comments

+1 Thank you this is awesome. Thank you for breaking down the way this works. What's a good resource I can use to learn Regex in Ruby? With problems/solutions so I can practice? I'm sadly oblivious to it.
You might want to have a look at this tutorial.
1

For the first url

url1 = "forum-351-page-2.html"

(1..30).each do |x|
  puts url1.sub(/page-\d*/, "page-#{x}")
end

This will output

"forum-351-page-1.html"
"forum-351-page-2.html"
"forum-351-page-3.html"
...
"forum-351-page-28.html"
"forum-351-page-29.html"
"forum-351-page-30.html"

You can do the same thing for the second url.

url1.sub(/page=\d*$/, "page=#{x}")

1 Comment

+1 for the simplicity. I gave the other answer the win since it breaks down the regex individual pieces. Thank you for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.