如何操作regex从文本返回url数组

How to manipulate regex to return array of URLs from text?

本文关键字:文本 返回 url 数组 regex 何操作 操作      更新时间:2023-09-26

我是Regex使用的新手,并且一直在寻找合适的Regex来从一段文本中检索url。

当前使用的正则表达式:

text.match(/(((ftp|https?):'/'/)(www'.)?|www'.)(['da-z-_'.]+)([a-z'.]{2,7})(['/'w'.-_'?'&]*)*'/?/g);

从一段文本中返回'www.mik'作为有效的URL,例如'…我的网页是www.mikealbert.com.. ',不适合我的目的。

,

到目前为止,以下正则表达式为我提供了匹配url的最佳结果('www.mik'不匹配,但'www.mikealbert.com'匹配)

/(https:[/][/]|http:[/][/]|www.)[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?'/?([a-zA-Z0-9'-'._'?',''/'''+&%'$#'=~])*$/.test("www.google.com");

但是,它只能用于匹配单个url。我该如何修改上面的正则表达式返回匹配的url数组?我还需要正则表达式来处理带有路径的url,例如www.facebook.com/abc123?apple=pie&blueberry=cake

谢谢你的帮助!

Remove $ sing from end of regex

var regex = /(https:[/][/]|http:[/][/]|www.)[a-zA-Z0-9'-'.]+'.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?'/?([a-zA-Z0-9'-'._'?',''/'''+&%'$#'=~])/g; 
var input = "https://stackoverflow.com/ lorem ipsum dolor sit amet http://google.com dolor sit amet www.foo.com"; 
if(regex.test(input)) {
  console.log(input.match(regex));
}

输出
[ 'https://stackoverflow.com/',
  'http://google.com',
  'www.foo.com' ]