2016-11-02 13 views
0

我一直很難想出如何解決這個問題。我有兩種URL,我需要能夠更新/增加頁面的數字值。識別提取並替換紅寶石中的字符串的一部分

URL 1:

forum-351-page-2.html 

在上面,我想修改這個網址爲n個頁面。所以我想創建一個新的網址,其範圍爲page-1到page-30。但這就是我想改變的一切。頁面n.html

地址2:

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

第二url不同,但我FEAL更容易訪問。

回答

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" 
+0

+1謝謝你,這真棒。感謝您打破這種工作方式。在Ruby中學習正則表達式有什麼好的資源?有問題/解決方案,我可以練習嗎?我很遺憾地忽略它。 – Doublespeed

+0

你可能想看看[本教程](http://www.regular-expressions.info/tutorial.html)。 –

1

對於第一個URL

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

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

這將輸出

"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" 

你可以做同樣的事情第二個網址。

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

1爲簡單起見。自從它打破了正則表達式的各個部分之後,我給出了另一個答案。感謝您的幫助。 – Doublespeed