[英]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.