【问题标题】:Regex match the Domain name正则表达式匹配域名
【发布时间】:2016-11-30 08:25:24
【问题描述】:

我需要从字符串中匹配域名。使用三种不同的模式。

var str=" with http match http://www.some.com and normal website type some.com and with www.some.com  ";
var url = /(http|ftp|https):\/\/[\w-]+(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/g;
console.log(str.match(url))

sn-p 以上只匹配http://www.some.com

但我需要匹配三种类型。

  1. http://www.some.com
  2. www.some.com
  3. some.com

帮我找到结果。我的正则表达式不太好。我从堆栈溢出中得到这个正则表达式模式。但不满足三个条件。

【问题讨论】:

  • 只需将(...) 分组并使用可选运算符?
  • 看我的回答,也有演示

标签: javascript regex match


【解决方案1】:

使用

(?:(http|ftp|https):\/\/)?[\w-]+(\.[\w-]+)+([\w.,@?^=%&;:\/~+#-]*[\w@?^=%&;\/~+#-])?

这只是使 http/ftp/... 可选(不捕获 ?:

在此处查看示例:demo

或图形here

【讨论】:

  • 注意! & 分别匹配 &(和号)、amp;。我猜不是故意的;)只需使用&
  • 我知道,我刚刚从 asker 复制了正则表达式
【解决方案2】:

如前所述,您可以使用()? 将正则表达式的某些部分设为可选,例如:(http:\/\/)?(www\.)?(some\.com)。所以用你的代码,可能是这样的:

var str=" with http match http://www.some.com and normal website type some.com and with www.some.com but matched http://----.-.-.-. and now will match ----.-.-.-.";
	var url = /((http|ftp|https):\/\/)?[\w-]*(\.[\w-]+)+([\w.,@?^=%&:\/~+#-]*[\w@?^=%&\/~+#-])?/g;
	console.log(str.match(url))

但是您提供的正则表达式匹配"http://----.-.-.-." 之类的字符串,并且通过此修改,它现在将匹配----.-.-.-.,例如,这不是您想要的。 如果你真的想匹配一个 URI,你需要使用不同的正则表达式。

这里有一些资源可以帮助您改进这个答案: https://regex.wtf/url-matching-regex-javascript/

请参阅引用 RFC 的What is the best regular expression to check if a string is a valid URL?http://www.faqs.org/rfcs/rfc3987.html

注意:它们似乎都匹配"http://----.-.-.-.",所以也许你的正则表达式并没有差多少。

【讨论】:

    【解决方案3】:

    要匹配 Unicode 字符,你应该使用这个:

    (ftp:\/\/|www\.|https?:\/\/)?[a-zA-Z0-9u00a1-\uffff0-]{2,}\.[a-zA-Z0-9u00a1-\uffff0-]{2,}(\S*)
    

    Demo here

    【讨论】:

      【解决方案4】:

      var pattern = /((https|http|ftp){1}:\/\/)?(www\.)?\w+\.\w{2,4}/ig;
      var test = ['http://www.some.com/NotRelevant',
        'https://www.some.com/NotRelevant',
        ':/www.some.com/NotRelevant',
        'www.some.com/NotRelevant',
        'some.com/NotRelevant'
      ];
      for (var t = 0; t < test.length; t++) {
        console.log(test[t], test[t].match(pattern));
      }

      【讨论】:

      • 也匹配:/www.some.com
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多