首页 > 解决方案 > 正则表达式从文本中提取 URL - Ruby

问题描述

我正在尝试urls从文本中检测并通过用引号括起来来替换它们,如下所示:

original text: Hey, it is a url here www.example.com
required text: Hey, it is a url here "www.example.com"

original text显示我的输入值并required text表示所需的输出。我在网上搜索了很多,但找不到任何可能的解决方案。我已经尝试过功能,但如果没有orURL.extract似乎无法检测到。以下是我要处理的一些 url 的示例。如果您知道解决方案,请告诉我。URLshttphttps

ANQUETIL-DUPERRON Abraham-Hyacinthe,KIEFFER Jean-Luc,www.hominides.net/html/actualites/outils-preuve-presence-hominides-asie-0422.php,Les Belles lettres,2001。

https://www.ancient-code.com/indian-archeologists-stumbleacross-ruins-great-forgotten-civilization-mizoram/

www.jstor.org/stable/24084454

www.biorespire.com/2016/03/22/une-nouvelle-villeantique-d%C3%A9couverte-en-inde/

insu.cnrs.fr/terre-solide/terre-et-vie/de-nouvellesdatations-repoussent-l-age-de-l-apparition-d-outils-surle-so

www.cerege.fr/spip.php?page=pageperso&id_user=94

标签: ruby-on-railsregexrubyruby-on-rails-4

解决方案


查找看起来像 url 的单词:

str = "ANQUETIL-DUPERRON Abraham-Hyacinthe, KIEFFER Jean-Luc, www.hominides.net/html/actualites/outils-preuve-presence-hominides-asie-0422.php,Les Belles lettres, 2001.\n\nhttps://www.ancient-code.com/indian-archeologists-stumbleacross-ruins-great-forgotten-civilization-mizoram/\n\nwww.jstor.org/stable/24084454\n\nwww.biorespire.com/2016/03/22/une-nouvelle-villeantique-d%C3%A9couverte-en-inde/\n\ninsu.cnrs.fr/terre-solide/terre-et-vie/de-nouvellesdatations-repoussent-l-age-de-l-apparition-d-outils-surle-so\n\nwww.cerege.fr/spip.php?page=pageperso&id_user=94"

str.split.select{|w| w[/(\b+\.\w+)/]}

这将为您提供一组没有空格的单词,并包含一个或多个.可能适用于您的用例的字符。

puts str.split.select{|w| w[/(\b+\.\w+)/]}
www.hominides.net/html/actualites/outils-preuve-presence-hominides-asie-0422.php,
https://www.ancient-code.com/indian-archeologists-stumbleacross-ruins-great-forgotten-civilization-mizoram/
www.jstor.org/stable/24084454
www.biorespire.com/2016/03/22/une-nouvelle-villeantique-d%C3%A9couverte-en-inde/
insu.cnrs.fr/terre-solide/terre-et-vie/de-nouvellesdatations-repoussent-l-age-de-l-apparition-d-outils-surle-so
www.cerege.fr/spip.php?page=pageperso&id_user=94

更新

修改字符串的完整解决方案:

str_with_quote = str.clone # make a clone for the `gsub!`

str.split.select{|w| w[/(\b+\.\w+)/]}
   .each{|url| str_with_quote.gsub!(url, '"' + url + '"')} 

现在您的克隆对象将 url 包含在双引号中

puts str_with_quote

会给你这个输出

ANQUETIL-DUPERRON Abraham-Hyacinthe, KIEFFER Jean-Luc, "www.hominides.net/html/actualites/outils-preuve-presence-hominides-asie-0422.php,Les" Belles lettres, 2001.

"https://www.ancient-code.com/indian-archeologists-stumbleacross-ruins-great-forgotten-civilization-mizoram/"

"www.jstor.org/stable/24084454"

"www.biorespire.com/2016/03/22/une-nouvelle-villeantique-d%C3%A9couverte-en-inde/"

"insu.cnrs.fr/terre-solide/terre-et-vie/de-nouvellesdatations-repoussent-l-age-de-l-apparition-d-outils-surle-so"

"www.cerege.fr/spip.php?page=pageperso&id_user=94"

推荐阅读