首页 > 解决方案 > 匹配字符串中多次出现的正则表达式

问题描述

是否可以匹配字符串中多次出现的正则表达式,例如,我想知道我的字符串是否包含多个 url,并且我想获得一个可用的结果,如数组:

"hey check out http://www.example.com and www.url.io".match(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+"))

会返回:

["http://www.example.com","www.url.io"]

console.log("hey check out http://www.example.com and www.url.io".match(new RegExp("([a-zA-Z0-9]+://)?([a-zA-Z0-9_]+:[a-zA-Z0-9_]+@)?([a-zA-Z0-9.-]+\\.[A-Za-z]{2,4})(:[0-9]+)?([^ ])+")))

也许有更好的方法来匹配网址,但我没有找到

标签: javascriptregex

解决方案


您可以尝试以下正则表达式:

/(http?[^\s]+)|(www?[^\s]+)/g

演示:

function urlify(text) {
  var urlRegex = /(http?[^\s]+)|(www?[^\s]+)/g;
  return text.match(urlRegex);
}

console.log(urlify("hey check out http://www.example.com and www.url.io"));


推荐阅读