2014-04-08 32 views
0

我有以下函數來測試傳遞給它的字符串是否與提供的正則表達式模式匹配。這似乎與我創建的其他驗證器功能正常工作。問題驗證VBA中的URL正則表達式

Private Function IsRegexMatch(ByRef sText As String, ByVal sPattern As String) As Boolean 
    IsRegexMatch = False 

    Dim regex As Object 
    Set regex = CreateObject("vbscript.regexp") 

    regex.IgnoreCase = True 
    regex.Global = True 
    regex.Pattern = sPattern 

    Set Matches = regex.Execute(sText) 
    If Matches.Count = 1 Then IsRegexMatch = True 

End Function 

然後我有以下函數來驗證網址。我知道,對於URL中的實際W3C規範要複雜得多,但對於我的應用程序的緣故,我只需要檢查以下內容:

  1. 使用HTTP或HTTPS
  2. 的站點/子有效
  3. 的網址並非指向根目錄(必須有附加了一些路徑)

    Public Function IsValidURL(ByRef sURL As String) As Boolean 
    
        IsValidURL = False 
    
        sPattern = "^" 'Beginning of string 
        sPattern = sPattern & "https?:\/\/" 'Protocol is http or https 
        sPattern = sPattern & "[\w\d][\w\d\-]*(\.[\w\d\-])*" 'Domain/Subdomain 
        sPattern = sPattern & "\.[\w]+" 'gTLD 
        sPattern = sPattern & "\/" 'we need to not be in the webroot 
        sPattern = sPattern & ".+" 'Check that we have stuff that comes after the slash 
    
        IsValidURL = IsRegexMatch(sURL, sPattern) 
    
    End Function 
    

出於某種原因,我不能讓過去我的第二個測試案例:

Private Sub Test_IsValidURL() 

    Debug.Assert IsValidURL("http://www.google.com/something") 
    Debug.Assert IsValidURL("https://www.google.com/something") 
    Debug.Assert IsValidURL("https://collab.mycompany.net/sites/hereweare") 

    Debug.Assert Not IsValidURL("http://www.google.com/") 
    Debug.Assert Not IsValidURL("https://collaboration") 
    Debug.Assert Not IsValidURL("ftp://collaboration") 
    Debug.Assert Not IsValidURL("htps://collaboration") 
    Debug.Assert Not IsValidURL("\\somemachine\somefolder") 
    Debug.Assert Not IsValidURL("\\somemachine\somefolder") 
    Debug.Assert Not IsValidURL("\\som.emachine\somefolder") 
    Debug.Assert Not IsValidURL("\\some.machin.e\somefolder") 
    Debug.Assert Not IsValidURL("\\some.machin.e\somefolder\folder2") 
    Debug.Assert Not IsValidURL("\\somemachine\somefolder\") 
    Debug.Assert Not IsValidURL("\\somemachine\somefolder\") 
    Debug.Assert Not IsValidURL("\\som.emachine\somefolder\") 
    Debug.Assert Not IsValidURL("\\some.machin.e\somefolder\") 
    Debug.Assert Not IsValidURL("\\some.machin.e\somefolder\folder2\") 
    Debug.Assert Not IsValidURL("\\4some.ma24chin.e124\somefolder\folder2\124") 
    Debug.Assert Not IsValidURL("my_file") 
    Debug.Assert Not IsValidURL("my_fi/le") 

    Debug.Print "PASSED: IsValidURL" 

End Sub 

我覺得我必須在那裏做一個愚蠢的錯誤,有人可以幫我嗎?

非常感謝:)

+0

爲什麼'「http://www.google.com/」'不是有效的網址?你聲稱它不是,當你在正則表達式中定義的時候它就是這樣的。那是故意的嗎?或者你需要拒絕帶有尾部的網址/或者你需要刪除不是;) –

+0

@Cor_Blimey我通過在模式的最後部分將「*」更改爲「+」來糾正該問題,但我仍然遇到第二種情況的問題。 – Ethan

回答

1

在 「站點/子」:

(\.[\w\d\-])* =>(\.[\w\d\-]+)*

剛剛測試過所有的情況下,在SublimeText此修正,它們都驗證/正確無效。

另外,如果是班級中的第一個或最後一個字符,則不需要轉義-

+0

謝謝!我應該抓住了這一點,但我想我一直在盯着這個屏幕太久。 – Ethan

+0

適用於我們所有人。 :) – tenub