小智 93
如果您喜欢使用Ruby中已经提供的内容:
require "uri"
URI.extract("text here http://foo.example.org/bla and here mailto:test@example.com and here also.")
# => ["http://foo.example.org/bla", "mailto:test@example.com"]
Run Code Online (Sandbox Code Playgroud)
阅读更多:http://railsapi.com/doc/ruby-v1.8/classes/URI.html#M004495
san*_*rvo 11
我用过twitter-text gem
require "twitter-text"
class UrlParser
include Twitter::Extractor
end
urls = UrlParser.new.extract_urls("http://stackoverflow.com")
puts urls.inspect
Run Code Online (Sandbox Code Playgroud)
你可以使用正则表达式和 .scan()
string.scan(/(https?:\/\/([-\w\.]+)+(:\d+)?(\/([\w\/_\.]*(\?\S+)?)?)?)/)
Run Code Online (Sandbox Code Playgroud)
您可以开始使用该正则表达式并根据您的需要进行调整.
失败的案例有哪些?
根据库regexpert,您可以使用
regexp = /(^$)|(^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$)/ix
Run Code Online (Sandbox Code Playgroud)
然后scan对文本执行 a 。
编辑:似乎正则表达式支持空字符串。只需删除首字母即可(^$)完成