簡體   English   中英

正則表達式匹配域名

[英]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匹配。

但是我需要匹配三種類型。

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

幫助我找到結果。我對regex不太滿意。我從堆棧溢出中獲得了此regex模式。 但是不滿足三個條件。

采用

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

這只是使http / ftp / ...是可選的(不捕獲?:

在此處查看示例: 演示

或作為圖形這里

如前所述,您可以使用()?將正則表達式的某些部分設為可選內容()? ,例如: (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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM