VBScript and RegEx (Regular Expressions)
'===========================================
' NAME: VBSCriptControlExcel.vbs
' AUTHOR: Neal Walters
' DATE : 3/19/2006
' http://VBScript-Training.com
'
' Related Regular Expression (RegEx) Websites:
'http://www.regular-expressions.info/
'http://regxlib.com/
' RegEx tester: http://regxlib.com/RETester.aspx
'===========================================
'-------Loop and show each match -------------
'http://www.microsoft.com/technet/scriptcenter/resources/qanda/apr05/hey0415.mspx
Set objRegEx = CreateObject("VBScript.RegExp")
objRegEx.Global = True
objRegEx.Pattern = "\d{4}"
strSearchString = "John=1234 Fred=5678 Susan=1212"
WScript.Echo "SearchString=" & strSearchString
Set colMatches = objRegEx.Execute(strSearchString)
If colMatches.Count > 0 Then
strMessage = "The following user accounts were found:" & vbCrlf
For Each strMatch In colMatches
strMessage = strMessage & strMatch.Value & " (character position=" & _
strMatch.FirstIndex & ")" & vbCrLf
Next
Else
WScript.Echo "No matches found"
End If
Wscript.Echo strMessage
'WScript.Quit
'-------Simple True/False Match -------------
'http://www.brettb.com/VBScriptRegularExpressions.asp
strSearchString = "Have you seen Microsoft.com web site lately?"
objRegEx.Pattern = "(.com|.org)"
objRegEx.IgnoreCase = True
objRegEx.Global = True
'Global property should be set to True if the search should match all occurrences of
'the pattern,
'or False if just the first occurrence should be matched:
expressionmatch = objRegEx.Test(strSearchString)
WScript.Echo "SearchString=" & strSearchString
WScript.Echo "Pattern=" & objRegEx.Pattern
WScript.Echo "express match = " & expressionmatch
'-------Replace -------------
InitialString = "www.foo.co.uk and www.zoo.co.uk"
objRegEx.Pattern = ".co.uk"
objRegEx.IgnoreCase = True
objRegEx.Global = True
ReplacedString = objRegEx.Replace(InitialString, ".com")
WScript.Echo "Replaced " & InitialString & " with " & ReplacedString
'WScript.Quit
'------ Strip HTML -------
'Create function
HTMLString = "<B>This <I>is </I>" & _
"<TT style=""background-color: rgb(0,255,255)"">some</TT> <FONT COLOR=#FF00FF> HTML</FONT></B>"
WScript.Echo "OriginalHTML=" & HTMLString
WScript.Echo "After Regex=" & StripHTMLTags(HTMLString)
Function StripHTMLTags(HTMLString)
objRegEx.Pattern = "<[^>]+>"
objRegEx.IgnoreCase = True
objRegEx.Global = True
stripHTMLtags = objRegEx.Replace(HTMLstring, "")
End Function
|