∟Example of Regular Expression Match and Replacement
This section provides a tutorial example of how to perform a pattern match and replacement with a regular expression using RegExp objects. Examples of sub matches are also included.
Now we ready to see a VBScript example of using a RegExp object to perform a pattern match with a regular expression:
<html>
<body>
<!-- regexp_match.html
- Copyright (c) 2015, HerongYang.com, All Rights Reserved.
-->
<pre>
<script language="vbscript">
Dim oRegExp
Set oRegExp = New RegExp
' A pattern to match any email address.
' 2 sub matches defined in the pattern.
oRegExp.Pattern = "(\w+)@(\w+)\.com"
' Repeat matches on the entire string
oRegExp.Global = True
' Ignore cases while matching the pattern
oRegExp.IgnoreCase = True
Dim sString
sString = "Please write to Me@HerongYang.com for help, " _
& "or Support@MicroSoft.COM to report bugs."
bFound = oRegExp.Test(sString)
document.writeln()
document.writeln("Any matches found: " & bFound)
Dim sCopy
sCopy = oRegExp.Replace(sString, "xxx@xxx.com")
document.writeln()
document.writeln("Email addresses replaced: " & sCopy)
Dim oMatches
Set oMatches = oRegExp.Execute(sString)
document.writeln()
document.writeln("Matches found: " & oMatches.Count)
For Each oMatch In oMatches
document.writeln(" Length = " & oMatch.Length)
document.writeln(" FirstIndex = " & oMatch.FirstIndex)
document.writeln(" Value = " & oMatch.Value)
For Each sSubMatch In oMatch.Submatches
document.writeln(" SubMatch = " & sSubMatch)
Next
Next
</script>
</pre>
</body>
</html>
Run this example code in IE, you will get:
Any matches found: True
Email addresses replaced:
Please write to xxx@xxx.com for help,
or xxx@xxx.com to report bugs.
Matches found: 2
Length = 17
FirstIndex = 16
Value = Me@HerongYang.com
SubMatch = Me
SubMatch = HerongYang
Length = 21
FirstIndex = 47
Value = Support@MicroSoft.COM
SubMatch = Support
SubMatch = MicroSoft
I hope this example covered everything you need to learn about regular expression in VBScript.