2015-04-05 89 views
-1

我有一個像下面這樣一個字符串:紅寶石先進GSUB

My first <a href="http://google.com">LINK</a> 
and my second <a href="http://yahoo.com">LINK</a> 

如何替換此字符串中的所有環節,從HREF =「URL」到HREF =「/重定向URL =網址是什麼? 「,使它變成

My first <a href="/redirect?url=http://google.com">LINK</a> 
and my second <a href="/redirect?url=http://yahoo.com">LINK</a> 

謝謝!

回答

2

鑑於你的情況下,我們可以構造以下的正則表達式:

re =/
    href=  # Match attribute we are looking for 
    [\'"]?  # Optionally match opening single or double quote 
    \K   # Forget previous matches, as we dont really need it 
    ([^\'" >]+) # Capture group of characters except quotes, space and close bracket 
/x 

現在你可以用字符串替換捕獲組你需要(使用\1來指代一組):

str.gsub(re, '/redirect?url=\1') 
+0

你不覺得你欠OP的正則表達式的解釋嗎?我建議你把它寫成多行'r = /.../ x',這樣你可以包含註釋,然後'str.gsub(r)'。我的答案[這裏](http://stackoverflow.com/questions/29216618/consistently-separate-values-in-array/29218517#29218517)給出了一個例子。 – 2015-04-05 21:06:36

+0

@CarySwoveland我的不好,補充說明。 – 2015-04-05 22:41:21

+0

這次你被原諒了。 – 2015-04-06 00:06:44

1

gsub讓你在替換匹配的正則表達式模式和使用捕獲的子串:

x = <<-EOS 
My first <a href="http://google.com">LINK</a> 
and my second <a href="http://yahoo.com">LINK</a> 
EOS 

x.gsub(/"(.*)"/, '"/redirect?url=\1"') # the \1 refers to the stuff captured 
             # by the (.*) 
+0

謝謝阿米特,但這並不能解決問題,因爲我可能在包含雙引號的字符串中包含其他詞。 – 2015-04-05 17:16:21

+0

您的問題還有其他未列出的約束條件嗎?您應該將它們添加到您的原始問題。 – 2015-04-05 17:54:52

+0

對不起,阿米特,你是什麼意思,約束?這是一個包含數據庫鏈接的簡單字符串。沒有更多...... – 2015-04-05 18:51:44