2017-06-10 19 views
0

我正在寫一個Python正則表達式來匹配網址。我寫了一個相當複雜的工作,工作得很好。我試圖讓主機名中的標籤部分根據我在維基百科上閱讀的內容更準確。無法得到這個'網址標籤'正則表達式準確

基本上如果你看到我的代碼片段,我有一個真值表來測試我寫的標籤部分。如果您想了解真值表,它基於主機名Wiki頁面中的「對主機名的限制」。

我只是不能得到情況1(字符串[0])工作,而沒有打破其他案件,並不能明白爲什麼情況1不會工作。我已經使用了調試工具,但所涉及的故障字符串對我來說太小,無法獲取任何重要信息。

請幫我解決一個我寫的問題,以便我知道我錯過了什麼。

如果您想知道爲什麼我不使用第三方庫來匹配網址,我正在學習正則表達式。

import re 

F = False 
T = True 

results = [T,F,T,F,F,F,T,F,T,F,F,F,F,F] 

strings = ['a','-','aa','--','-a','a-','aaa','aa-','a-a','a--','-aa','-a-','--a','---'] 

x = list(range(len(strings))) 

regex_test = r'(?P<Label>(?P<Label_start>[a-zA-Z0-9])((?P<Label_mid>[a-zA-Z0-9-]{1,61})?)(?=(?P<Label_end>[a-zA-Z0-9](?=[./])))(?P=Label_end)?)\.' 

if len(strings) == len(results): 
    for n in x: 
     if results[n] == bool(re.match(pattern = regex_test, string = strings[n] + '.')): 
      print("Works.") 
      if results[n] == True: 
       print(re.match(pattern = regex_test, string = strings[n] + '.').groupdict()) 
     else: 
      print("Bug for: " + strings[n]) 
      #print(str(re.match(pattern = regex_test, string = strings[n] + '.',flags=re.DEBUG))) 
+0

[與正則表達式的域名驗證]的可能的複製(https://stackoverflow.com/questions/10306690/domain-name-validation-with-regex) –

+0

我的正則表達式幾乎是準確的。請指出爲什麼正則表達式無法匹配單個字符。這會幫助我理解我的正則表達式出錯的地方。非常感謝。另外,我只需要標籤而不是主機名就可以獲得幫助。 '。'被用作結束標誌,因爲這個正則表達式後面會跟隨其餘的主機名正則表達式,然後是URL正則表達式的其餘部分。 –

+0

我會嘗試在你的regex上玩regex101.com。也可以嘗試簡化語法(排除命名組)以嘗試發現錯誤。您可以稍後將它們添加回來。 –

回答

0

有時候使用python會更容易(也更易讀)!但是,有一部分域名驗證可從re中受益。看到我的嘗試here,或我下面的完整snipett。

# What are valid hostnames? 
# (1) Series of labels separated by periods. 
# (2) Each label can contain only letters, numbers and hyphens. 
# (3) Each label can not start or end with a hyphen. 
# (4) Each label can be 1-63 characters 
# (5) Entire domain cannot be longer than 253 characters. 

import re 

domains = ['en.wikipedia.org', 
      'my.his-site.com', 
      '-bad.site-.5345'] 

def is_valid_hostname(domain): 
    # Utilize rule 1 to split into labels. 
    labels = domain.split('.') 

    for label in labels: 
     # Check rules 2 and 3. 
     if not re.search(r'^[A-z0-9][A-z0-9\-]*[A-z0-9]$', label): 
      return False 

     # Check rule 4. 
     if not (0 < len(label) < 64): 
      return False 

    # Check rule 5. 
    if len(domain) > 253: 
     return False 

    return True 


for domain in domains: 
    if is_valid_hostname(domain): 
     print('{}:\tvalid'.format(domain)) 
    else: 
     print('{}:\tinvalid'.format(domain)) 
+0

這將是一個更大的正則表達式的一部分。我只需要這個作爲正則表達式。此外,目前域名長度並不是一個考慮因素。但是謝謝你超時並理解我的問題。 –

+0

所以你想要一個正則表達式唯一的解決方案?在這種情況下,'^ [0-9 \ p {L}] [0-9 \ p {L} - \。] {1,61} [0-9 \ p {L}] \。[0-9 \ p {L}] [\ p {L} - ] * [0-9 \ p {L}] + $'會完成這項工作(請參閱重複的https://stackoverflow.com/a/38477788/1713185) –

相關問題