从文本中提取 URL 的正则表达式 - Ruby

regex to extract URLs from text - 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 代表所需的输出。我在网上搜索了很多但找不到任何可能的解决方案。我已经尝试过 URL.extract 功能,但在没有 httphttps 的情况下似乎无法检测到 URLs。以下是我要处理的一些网址的示例。如果您知道解决方案,请告诉我。

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

查找与 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"