【问题标题】:Match multiple occurances of regular expressions in a string [duplicate]匹配字符串中多次出现的正则表达式[重复]
【发布时间】:2020-06-07 13:49:55
【问题描述】:

是否可以匹配字符串中多次出现的正则表达式,例如,我想知道我的字符串是否包含多个 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]+)?([^ ])+")))

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

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    你可以试试下面的正则表达式:

    /(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"));

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      • 2015-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多