【问题标题】:Strip all domains except one from string从字符串中删除除一个之外的所有域
【发布时间】:2018-04-16 22:52:02
【问题描述】:

我得到了像“facebook.com somenickname google.com example.com”这样的字符串。我的意思是有一个字符串可以包含多个 url 和我的域 - example.com。我想从该字符串中删除除“example.com”之外的所有网址,因此输出将类似于“somenickname example.com”

我尝试使用以下正则表达式,但不知道如何排除我的域。

string.replace(/(https?:\/\/)?(www.)?[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}\/?/i, '').trim()

感谢您的帮助!

【问题讨论】:

    标签: javascript node.js regex


    【解决方案1】:

    您可以为此任务使用带有单词边界的否定前瞻。

    var re = /\b(?!example\.com)(https?:\/\/)?(www.)?[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}\/?\b/g;
    var str = 'facebook.com somenickname google.com example.com';
    console.log(str.replace(re, '')); // replace matches
    console.log(str.replace(re, '').replace(/\s+/g, ' ')); // also replace space chars
    • 负前瞻(?!example\.com)。断言下面的正则表达式不匹配
      • example 与字符 example 逐字匹配(区分大小写)
      • \. 匹配字符 . 字面意思(区分大小写)
      • com 与字符 com 逐字匹配(区分大小写)

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 2011-06-23
      • 2018-07-08
      • 1970-01-01
      • 1970-01-01
      • 2015-11-24
      • 2011-11-08
      • 1970-01-01
      • 2012-11-03
      相关资源
      最近更新 更多