Ruby 提取并添加到字符串中URL的链接

Ruby 提取并添加到字符串中URL的链接,ruby,string,url,replace,Ruby,String,Url,Replace,我有几个字符串,其中有链接。例如: var str = "I really love this site: http://www.stackoverflow.com" 我需要添加一个链接标签,这样str将: I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a> 我真的很喜欢这个网站: 一种可能是使用来让它进行解析。大致如下: re

我有几个字符串,其中有链接。例如:

var str = "I really love this site: http://www.stackoverflow.com"
我需要添加一个链接标签,这样str将:

I really love this site: <a href="http://www.stackoverflow.com">http://www.stackoverflow.com</a>
我真的很喜欢这个网站:

一种可能是使用来让它进行解析。大致如下:

require 'uri'

str = "I really love this site: http://www.stackoverflow.com"
url = str.slice(URI.regexp(['http']))
puts str.gsub( url, '<a href="' + url + '">' + url + '</a>' )
require'uri'
str=“我真的很喜欢这个网站:http://www.stackoverflow.com"
url=str.slice(URI.regexp(['http']))
放置str.gsub(url“”)

您可以为此使用URI.extract:

str = "I really love this site: http://www.stackoverflow.com and also this one: http://www.google.com"

URI.extract(str, ['http', 'https']).each do |uri|
  str = str.gsub( uri, "<a href=\"#{uri}\">#{uri}</a>" )
end

str
str=“我真的很喜欢这个网站:http://www.stackoverflow.com 还有这个:http://www.google.com"
提取(str,['http','https'])。每个都做| URI|
str=str.gsub(uri,“”)
结束
str

上述内容还可以在一个字符串中匹配多个URL。

在这里,工作代码:)也会在显示的链接中删除http/s前缀

注意,您应该在uri+“”上使用正则表达式,以便它正确捕获链接。。。然后,您需要在开始处添加一个空格,以捕获结尾处没有尾随空格的链接

thisString = yourString+" " # add space to catch link at end
URI.extract(thisString, ['http', 'https']).each do |uri|
  linkURL = uri
  if(uri[0..6] == "http://")
    linkURL = uri[7..-1]
  elsif(uri[0..7] == "https://")
    linkURL = uri[8..-1]
  end
  thisString = thisString.gsub( uri+" ", "<a href=\"#{uri.to_s}\">#{linkURL.to_s}</a> " )
end
thistring=yourString+“”#在末尾添加空格以捕捉链接
extract(thistring,['http','https'])。每个都有| URI|
linkURL=uri
如果(uri[0..6]=“http://”)
linkURL=uri[7..-1]
elsif(uri[0..7]=“https://”)
linkURL=uri[8..-1]
结束
thisString=thisString.gsub(uri+“”,“”)
结束

您可以像这里描述的那样使用actionpack:可能重复的