Ruby 高级 gsub

Ruby advanced 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://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="') # the  refers to the stuff captured 
                                       # by the (.*)

鉴于您的情况,我们可以构建以下正则表达式:

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

现在您可以用您需要的字符串替换捕获的组(使用 </code> 引用组):</p> <pre><code>str.gsub(re, '/redirect?url=')