在VBA Regex中发布验证URL

时间:2014-04-08 17:36:48

标签: regex vba url access-vba

我有以下函数来测试传递给它的字符串是否与提供的正则表达式模式匹配。这似乎与我创建的其他验证器功能一起正常工作。

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。我知道URL的实际W3C规范要复杂得多,但为了我的应用程序,我只需要检查以下内容:

  1. 使用HTTP或HTTPS
  2. 域/子域名有效
  3. 网址未指向webroot(必须附加一些路径)

    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
    
  4. 出于某种原因,我无法通过我的第二个测试用例:

    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
    

    我觉得我必须在某处发生愚蠢的错误,有人可以帮助我吗?

    非常感谢:)

1 个答案:

答案 0 :(得分:1)

在“域/子域名”下:

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

刚刚使用此更正在SublimeText中测试了所有案例,它们都正确验证/无效。

此外,如果它是班级中的第一个或最后一个角色,则无需转义-