2016-11-30 166 views
0

我需要匹配域名形式的字符串。有三种不同的模式。正则表达式匹配域名

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.,@?^=%&:\/~+#-]*[\[email protected]?^=%&\/~+#-])?/g; 
 
console.log(str.match(url))

上面的代码中的比赛只有http://www.some.com

但我需要匹配三种类型。

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

帮我找到result.I不是在regex.I很好地得到堆栈溢出这个正则表达式。但对三个条件不满意。

+2

只是组'(...)'的前缀和使用可选运算符'?' – Fallenhero

+0

看到我的答案,还有一个演示它以及 – Fallenhero

回答

2

使用

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

这只是使HTTP/FTP/...可选(无捕获?:

看到这里的例子:demo

或图形here

+0

注意!'&'分别与'&'(&符),'a','m','p'和';'相匹配。没有打算我猜;)只需使用&&。 – ClasG

+0

我知道,我只是复制从提问者的正则表达式 – Fallenhero

0

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

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

Demo here

-1

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)); 
 
}

+0

也匹配':/ www.some.com' – Fallenhero

1

正如之前所说,可以使正则表达式可选的()?,例如一些地方:(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 ----.-.-.-."; 
 
\t var url = /((http|ftp|https):\/\/)?[\w-]*(\.[\w-]+)+([\w.,@?^=%&amp;:\/~+#-]*[\[email protected]?^=%&amp;\/~+#-])?/g; 
 
\t console.log(str.match(url))

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

这里有一些资源,帮助您提高这样的回答: https://regex.wtf/url-matching-regex-javascript/

看到What is the best regular expression to check if a string is a valid URL?在RFC为引用:http://www.faqs.org/rfcs/rfc3987.html

注:他们似乎都匹配"http://----.-.-.-.",也许您正则表达式并不多更差。