2015-04-05 91 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