【问题标题】:Build an array of matching links构建一组匹配的链接
【发布时间】:2011-06-20 22:27:34
【问题描述】:

我正在使用 Ruby on Rails 3.0.7,我想从 string(或 text)中“提取”其中存在的所有链接。

此时我有以下正则表达式*以匹配 URL 和电子邮件地址:

/((\S+)?(@|mailto\:)|((ht|f)tp(s?)\:\/\/)|([www]))\S+/

如果我有以下字符串

text here http://www.sitename.com and text here www.sitename.com and text here email@sitename.com and text here

我想获得一个数组(或其他一些数据结构),其中包含上述字符串中存在的链接。

我该怎么办?


*顺便说一句:正则表达式“好”吗?

【问题讨论】:

    标签: ruby-on-rails ruby regex arrays string


    【解决方案1】:

    可能是这样的:

    text = 'text here http://www.sitename.com and text here www.sitename.com and text here email@sitename.com and text here'
    links = []
    text.split.each do |word|
      links << word if word.match(/(((\S+)?)((@|mailto\:)|(((ht|f)tp(s?))\:\/\/)|([www]))\S+)/)
    end
    puts links
    

    【讨论】:

      猜你喜欢
      • 2010-09-27
      • 2020-11-03
      • 1970-01-01
      • 2014-02-05
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多