Ruby高级gsub

Ruby高级gsub,ruby,string,gsub,Ruby,String,Gsub,我有一根像下面这样的线: My first <a href="http://google.com">LINK</a> and my second <a href="http://yahoo.com">LINK</a> 我的第一个 还有我的第二个 如何替换此字符串中从href=“URL”到href=“/redirect?URL=URL”的所有链接,使其成为 My first <a href="/redirect?url=http://goo

我有一根像下面这样的线:

My first <a href="http://google.com">LINK</a>
and my second <a href="http://yahoo.com">LINK</a>
我的第一个
还有我的第二个
如何替换此字符串中从href=“URL”到href=“/redirect?URL=URL”的所有链接,使其成为

My first <a href="/redirect?url=http://google.com">LINK</a>
and my second <a href="/redirect?url=http://yahoo.com">LINK</a>
我的第一个
还有我的第二个

谢谢

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 (.*)

x=根据您的情况,我们可以构造以下正则表达式:

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
引用组):


谢谢你,阿米特,但这并不能解决问题,因为我可能会在包含双引号的字符串中使用其他单词。你的问题还有哪些未声明的约束条件?你应该把它们添加到你原来的问题中。对不起,阿米特,你说的约束是什么意思?它是一个包含数据库链接的简单字符串。除此之外,Manuel,
将x.gsub(/“(.*)”/,“/redirect?url=\1”)#=>“我的第一个…链接和第二个…链接”
,这是您要求的结果。Amit假设,通过您的评论,您的意思是,如果字符串末尾添加了
“cat's have nine life”
,则需要相同的结果。这个问题并没有把它作为一个要求,所以他希望这个问题更加精确。你不认为你应该向OP解释一下正则表达式吗?我建议您编写多行
r=/…/x
,这样就可以包含注释,然后
str.gsub(r)
。我的回答给出了一个例子。@CarySwoveland My bad,补充了一个解释。这次你被原谅了。
str.gsub(re, '/redirect?url=\1')