[英]Regex match the Domain name
我需要用三个不同的模式来匹配域名形式的字符串。
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))
以上摘要仅与http://www.some.com
匹配。
但是我需要匹配三种类型。
http://www.some.com
www.some.com
some.com
帮助我找到结果。我对regex不太满意。我从堆栈溢出中获得了此regex模式。 但是不满足三个条件。
如前所述,您可以使用()?
将正则表达式的某些部分设为可选内容()?
,例如: (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://----.-.-.-."
类的字符串"http://----.-.-.-."
,并进行了修改,现在将匹配----.-.-.-.
例如,这不是您想要的。 如果您确实要尝试匹配URI,则需要使用其他正则表达式。
以下是一些可帮助您改善此答案的资源: https : //regex.wtf/url-matching-regex-javascript/
请参阅什么是检查字符串是否为有效URL的最佳正则表达式? 引用RFC的位置: http : //www.faqs.org/rfcs/rfc3987.html
注意:它们似乎都与"http://----.-.-.-."
匹配"http://----.-.-.-."
,因此您的正则表达式可能并不差。
要匹配Unicode字符,应使用以下字符:
(ftp:\/\/|www\.|https?:\/\/)?[a-zA-Z0-9u00a1-\uffff0-]{2,}\.[a-zA-Z0-9u00a1-\uffff0-]{2,}(\S*)
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)); }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.