Regular Expressions in VbScript?

后端 未结 5 1302
谎友^
谎友^ 2020-12-18 16:02

Does VbScript have a native implementation for Regex? I need to validate e-mail addresses on an old ASP application.

Any pointers would be great.

相关标签:
5条回答
  • 2020-12-18 16:33

    Yes, it sure does. Here's Microsoft's documention.

    0 讨论(0)
  • 2020-12-18 16:33

    VBScript has a built-in RegExp object, which is Microsoft's implementation of JavaScript regular expressions. I have an article about the VBScript RegExp object on my website that explains how to use it.

    0 讨论(0)
  • 2020-12-18 16:47

    Since the top answer here is in VB6 I thought I'd add one here in VBScript (since that's what the question is asking for):-

    Option Explicit
    
    Function GetEmailValidator()
    
      Set GetEmailValidator = New RegExp
    
      GetEmailValidator.Pattern = "^((?:[A-Z0-9_%+-]+\.?)+)@((?:[A-Z0-9-]+\.)+[A-Z]{2,4})$"
    
      GetEmailValidator.IgnoreCase = True
    
    End Function
    
    Dim EmailValidator : Set EmailValidator = GetEmailValidator()
    

    Now some tests:-

    Response.Write EmailValidator.Test("") = False
    Response.Write EmailValidator.Test(" ") = False
    Response.Write EmailValidator.Test("somebody@domain.co.uk") = True
    Response.Write EmailValidator.Test("someone@domain.com") = True
    Response.Write EmailValidator.Test("some.body@domain.co.uk") = True
    Response.Write EmailValidator.Test("broken@domain..co.uk") = False
    Response.Write EmailValidator.Test("@oops.co.uk") = False
    Response.Write EmailValidator.Test("name") = False
    Response.Write EmailValidator.Test("name@uk") = False
    Response.Write EmailValidator.Test("name@uk") = False
    Response.Write EmailValidator.Test("name@domain.abcde") = False
    
    0 讨论(0)
  • 2020-12-18 16:47

    Like other said, yes. I just wanted to put you at the devguru vbscript docs, I find they tend to be the good place to get quick vbscript answers. This is there section on the Regexp object.

    0 讨论(0)
  • 2020-12-18 16:48

    This example is by AlexCuse from LessThanDot

    Function ValidEmail(ByVal emailAddress) 
    
    'this function will use regular expressions to check an '
    'email address for validity '
    
    'instantiate regex object container, output boolean '
    Dim objRegEx, retVal 
    
    'using late binding, vbscript reference is not required '
    Set objRegEx = CreateObject("VBScript.RegExp") 
    
    '.pattern -looks for a valid email address '
    With objRegEx 
          .Pattern = "^\b[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$" 
          .IgnoreCase = True 
    End With 
    
    retVal = objRegEx.Test(emailAddress) 
    
    'get rid of RegEx object '
    Set objRegEx = Nothing 
    
    ValidEmail = retVal 
    
    End Function
    
    0 讨论(0)
提交回复
热议问题