在 Ruby 中提取字符串中的所有 url [英] Extract all urls inside a string in Ruby

查看:31
本文介绍了在 Ruby 中提取字符串中的所有 url的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些文本内容,其中包含一个 URL 列表.

I have some text content with a list of URLs contained in it.

我正在尝试获取所有 URL 并将它们放入一个数组中.

I am trying to grab all the URLs out and put them in an array.

我有这个代码

content = "Here is the list of URLs: http://www.google.com http://www.google.com/index.html"

urls = content.scan(/^(http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.*)?$/ix)

我试图得到最终结果:

['http://www.google.com', 'http://www.google.com/index.html']

上面的代码似乎无法正常工作.有谁知道我做错了什么?

The above code does not seem to be working correctly. Does anyone know what I am doing wrong?

谢谢

推荐答案

一种不同的方法,与完美是善的敌人思想不同:

A different approach, from the perfect-is-the-enemy-of-the-good school of thought:

urls = content.split(/\s+/).find_all { |u| u =~ /^https?:/ }

这篇关于在 Ruby 中提取字符串中的所有 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆