在Ruby中提取URL(到数组)
下午好 我正在学习如何在Ruby中使用正则表达式,现在我需要一些帮助。 我正在尝试从字符串中提取0到多个URL 这是我正在使用的代码:在Ruby中提取URL(到数组),ruby,regex,string,Ruby,Regex,String,下午好 我正在学习如何在Ruby中使用正则表达式,现在我需要一些帮助。 我正在尝试从字符串中提取0到多个URL 这是我正在使用的代码: sStrings = ["hello world: http://www.google.com", "There is only one url in this string http://yahoo.com . Did you get that?", "The first URL in this string is http://www.bing.com an
sStrings = ["hello world: http://www.google.com", "There is only one url in this string http://yahoo.com . Did you get that?", "The first URL in this string is http://www.bing.com and the second is http://digg.com","This one is more complicated http://is.gd/12345 http://is.gd/4567?q=1", "This string contains no urls"]
sStrings.each do |s|
x = s.scan(/((http|https):\/\/[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,5}(([0-9]{1,5})?\/.[\w-]*)?)/ix)
x.each do |url|
puts url
end
end
这是返回的内容:
http://www.google.com
http
.google
nil
nil
http://yahoo.com
http
nil
nil
nil
http://www.bing.com
http
.bing
nil
nil
http://digg.com
http
nil
nil
nil
http://is.gd/12345
http
nil
/12345
nil
http://is.gd/4567
http
nil
/4567
nil
只提取完整URL而不提取正则表达式部分的最佳方法是什么?您可以使用匿名捕获组(?:…)而不是(…)
我知道您这样做是为了学习正则表达式,但是如果您真的想从字符串中提取URL,请查看
URI.extract
,它从字符串中提取URI。(需要“uri”
才能使用它)您可以使用匿名捕获组(?:)而不是(…)
我知道您这样做是为了学习正则表达式,但是如果您真的想从字符串中提取URL,请查看
URI.extract
,它从字符串中提取URI。(需要“uri”
才能使用它)您可以使用(?:SUB_模式)
创建非捕获组。下面是一个例子,其中加入了一些额外的简化。另外,由于您使用的是/x
选项,因此可以通过以可读的方式排列正则表达式来利用它
sStrings = [
"hello world: http://www.google.com",
"There is only one url in this string http://yahoo.com . Did you get that?",
"... is http://www.bing.com and the second is http://digg.com",
"This one is more complicated http://is.gd/12345 http://is.gd/4567?q=1",
"This string contains no urls",
]
sStrings.each do |s|
x = s.scan(/
https?:\/\/
\w+
(?: [.-]\w+ )*
(?:
\/
[0-9]{1,5}
\?
[\w=]*
)?
/ix)
p x
end
这对于学习来说是很好的,但是不要试图用这种方式匹配URL。有这样的工具。您可以使用
(?:SUB_模式)
创建一个非捕获组。下面是一个例子,其中加入了一些额外的简化。另外,由于您使用的是/x
选项,因此可以通过以可读的方式排列正则表达式来利用它
sStrings = [
"hello world: http://www.google.com",
"There is only one url in this string http://yahoo.com . Did you get that?",
"... is http://www.bing.com and the second is http://digg.com",
"This one is more complicated http://is.gd/12345 http://is.gd/4567?q=1",
"This string contains no urls",
]
sStrings.each do |s|
x = s.scan(/
https?:\/\/
\w+
(?: [.-]\w+ )*
(?:
\/
[0-9]{1,5}
\?
[\w=]*
)?
/ix)
p x
end
这对于学习来说是很好的,但是不要试图用这种方式匹配URL。有一些工具可以做到这一点