Regular Expressions in VbScript? - regex

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.

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

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

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

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.

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.

Related

VB6 Like operator not picking up space character

I have a legacy app whereby email addresses are validated using a RegEx experssion passed to VB6 and then compared using the Like operator
The RegEx expression is still allowing space characters to be included in the email address which I do not want.
The code below - I want the first to retru True but the second to return False. What amendment to I need to make to the RegEx expression?
Sub LikeTest()
MsgBox "hello#hello.com" Like "[A-Za-z0-9-\.\]*#*[A-Za-z0-9-\.\].*[A-Za-z]" 'returns True
MsgBox "hello# hello.com" Like "[A-Za-z0-9-\.\]*#*[A-Za-z0-9-\.\].*[A-Za-z]" 'returns True but should return False
End Sub
DIM test
test = LikeTest("hello#hello.com")
Function LikeTest(sEmail)
RegExpTest = false
Dim regEx, retVal
Set regEx = New RegExp
' Create regular expression:
regEx.Pattern ="^[\w-\.]{1,}\#([\da-zA-Z-]{1,}\.){1,}[\da-zA-Z-]{2,3}$"
' Set pattern:
regEx.IgnoreCase = true
' Set case sensitivity.
retVal = regEx.Test(sEmail)
' Execute the search test.
If not retVal Then
RegExpTest = false
else
RegExpTest = true
End If
MsgBox(RegExpTest)
End Function
Source:
https://web.archive.org/web/20061026092253/http://www.4guysfromrolla.com/aspfaqs/ShowFAQ.asp?FAQID=47

Regex using Interval Matching (Exact or Range)

I'm trying to use the regex feature of Ms Access 2007 VBA but I'm doing something wrong.
If I have a regex of:
\$\d{3,5}\.\d{2}
The following gives me a True: $123.45
And these give me False: $12.23 or $123456.45
So all is good with this.
However, if I now test this, it gives me True !?
$123.456
Isn't the second section of my regex, ie \d{2} stating that I can only have two digits after the decimal/period?
This problem also occurs even if I put a boundary, ie \d{2,2}
Sorry; figured it out. I used the boundaries functionality.
Therefore the following now works:
\$\d{3,5}\.\b\d{2}\b
If there are any other thoughts or suggestions I'd still be more than grateful
' you confirmed you don't want this ...
? RegExpTest("$123.456", "\$\d{3,5}\.\d{2}")
True
' you can add "$" to the regex pattern ...
? RegExpTest("$123.456", "\$\d{3,5}\.\d{2}$")
False
Function RegExpTest(ByVal pSource As String, _
ByVal pPattern As String) As Boolean
Dim re As Object ' New RegExp
Set re = CreateObject("VBScript.RegExp")
With re
.Pattern = pPattern
.IgnoreCase = True
.Global = False
.MultiLine = False
End With
RegExpTest = re.Test(pSource)
Set re = Nothing
End Function

Using RegEx to search a table for missing information doesn't extract all matching values

I am a little new to VBA, and I did try searching the forums for this topic but I am not sure I used the right words to search. Here is my question:
I am using VBA to extract missing information with regexp. Say I have a table with text which contains phone and fax numbers. I would like to collect the numbers into a table. So far, the code I have works OK, but when I have multiple numbers (say regular and 800 #s) for some reason, only one number is retrieved, not the others. How can I get all the results to be added to the table?
Query:
SELECT regxtr([Table1]![field1]) AS phone FROM Table1;
VBA code for (regxtr)function:
Option Compare Database
Function regxtr(ByVal Target As String) As String 'Target is the field we are 'extracting from
Dim re As New RegExp
Dim oMatches As Object
Dim oMatch As Object
Dim n As Long
n = 0
'Set re = CreateObject("vbscript.regexp")
With re
.Global = True
.IgnoreCase = True
.Multiline = True
.Pattern = "(\d\d\d.\d\d\d\.\d\d\d\d)" 'keeping the pattern simple for now just to test
End With
'test before executing
If re.Test(Target) = True Then
Set oMatches = re.Execute(Target)
'attempt to get all matches. THIS IS WHERE I AM FAILING
For n = 0 To oMatches.Count - 1
Set oMatch = oMatches(n)
regxtr = oMatch.Value
n = n + 1 ' does this even belong here?
Next
End If
End Function
How can I get to so all matches will populate the field [phone] in the query? Any help would be greatly appreciated.
First of all, a correction in terminology. You're not looking for 'submatches' (also called 'capturing groups' in other regex implementations). You're looking for 'matches' for your regex, so you can drop the parentheses and just use \d{3}.\d{3}.\d{4} That said, this may be what you need:
Function regxtr(ByVal Target As String) As String 'Target is the field we are 'extracting from
Dim re As New RegExp
Dim oMatches As Object
Dim oMatch As Object
With re
.Global = True
.IgnoreCase = True
.Multiline = True
.Pattern = "\d{3}.\d{3}.\d{4}" 'keeping the pattern simple for now just to test
End With
If re.Test(Target) = True Then
Set oMatches = re.Execute(Target)
For Each oMatch In oMatches 'Note: you may get multiple matches because you set re.Global = True above, otherwise you would only get the first match
regxtr = regxtr & " " & oMatch 'Note: this is awkward and not advisable as a way to return the values. This is just an example.
Next oMatch
End If
End Function
As a test:
?regxtr("foo 993-242.1231bar994.425-1234hello987.234.2424 world 999.342-5252")
993-242.1231 994.425-1234 987.234.2424 999.342-5252

RegEx in Classic ASP to find out if the URL has a particular string

I have to do a site redirect through script for about 10 different URLS all containing the string "enterpriseloyalty". I'm trying to write some RegEx to find out if the URL has this in it. To do so, I'm using a function I found on another question here (using classic asp for regular expression). The problem is that nothing is returning when I test it on the site "http://enterpriseloyaltyjournal.ca/".
I've tested the regex in both http://gskinner.com/RegExr/ and http://www.pagecolumn.com/tool/regtest.htm with matching results of the regex "enterpriseloyalty[A-Za-z]*(?=.{1,1})" working, matching "enterpriseloyaltyjournal" in the URL string. But on the site, "Response.Write("Results: " & result.Submatches(0))" returns nothing at all. And to be honest, I don't know if I am expecting a result of the matching string or what, but there's just nothing at all returned.
When I just do an If InStr(Request.ServerVariables("SERVER_NAME"),"enterpriseloyaltyjournal.ca") > 0 Then statement, it comes back true. My code is below. Any help is greatly appreciated.
Function RegExResults(strTarget, strPattern)
Set regEx = New RegExp
regEx.Pattern = strPattern
regEx.Global = true
Set RegExResults = regEx.Execute(strTarget)
Set regEx = Nothing
End Function
'Pass the original string and pattern into the function and get a collection object back'
Set arrResults = RegExResults(Request.ServerVariables("SERVER_NAME"), "enterpriseloyalty[A-Za-z]*(?=\.{1,1})")
'In your pattern the answer is the first group, so all you need is'
For each result in arrResults
Response.Write("Results: " & result.Submatches(0))
Next
EDIT
I'm also trying the following with no results:
Regex.IgnoreCase = True
Regex.Pattern = "enterpriseloyalty[A-Za-z]*(?=\.{1,1})"
Response.Write("Results:" & Regex.Test(Request.ServerVariables("SERVER_NAME")))
Also, when I say "no results", I mean nothing at all is returned. Not even the "Results:" portion. Though I'm not getting any type of error.
SOLVED
Changed the above code to look like:
Dim regex
Set regex = New RegExp
regex.IgnoreCase = True
regex.Pattern = "enterpriseloyalty[A-Za-z]*(?=\.{1,1})"
Response.Write("Results:" & regex.Test(Request.ServerVariables("SERVER_NAME")))
And it worked just fine.
Found another way of doing it, and ended up using:
Dim regex
Set regex = New RegExp
regex.IgnoreCase = True
regex.Pattern = "enterpriseloyalty[A-Za-z]*(?=\.{1,1})"
Response.Write("Results:" & regex.Test(Request.ServerVariables("SERVER_NAME")))

Regular Expressions in MS Access VBA?

I definitely like MS Access as an RAD-Tool for small-scope data-driven applications. But one thing I really miss as a .Net-Developer is Regular Expressions. They really come in handy when validating user input. I really do not know why Microsoft did not put these in the standard VBA-Library.
Is there a way to use Regular Expressions in MS Access VBA?
You can use the VBScript Regex Object by adding a reference to the Microsoft VBScript Regular Expressions library.
Example usage:
Dim szLine As String
Dim regex As New RegExp
Dim colregmatch As MatchCollection
With regex
.MultiLine = False
.Global = True
.IgnoreCase = False
End With
szLine = "Analyzed range (from-to) 10 100"
regex.Pattern = "^Analyzed range"
If regex.Test(szLine) Then
regex.Pattern = ".*?([0-9]+).*?([0-9]+)"
Set colregmatch = regex.Execute(szLine)
'From
Debug.Print colregmatch.Item(0).submatches.Item(0)
'To
Debug.Print colregmatch.Item(0).submatches.Item(1)
End If
Source: http://mark.biek.org/blog/2009/01/regular-expressions-in-vba/
You can use CreateObject("vbscript.regexp") or just reference the scripting library.