Regular Expressions in VBScript - Searching and Replacing
(Page 2 of 4 )
On the surface, regular expressions just match a string of characters. For instance, the regular expression “word” would match the letters w-o-r-d in both “word” and “sword.” Replacements are simply string substitutions. You provide the substitution and VBScript’s RegExp object makes a replacement when it finds matches.
strTest = "This is my test string."
Set objRegExp = New RegExp
objRegExp.IgnoreCase = True
objRegExp.Pattern = "test"
If objRegExp.Test(strTest) Then WScript.Echo "A match was found."
The RegExp object’s Test method returns a Boolean value that indicates whether a match was found. It requires one parameter—a text string to perform the test against. In this example, Test returns a value of True because the pattern “test” can be found in the string.
strTest = "This is my test string."
Set objRegExp = New RegExp
objRegExp.IgnoreCase = True
objRegExp.Pattern = "test"
Set colMatches = objRegExp.Execute(strTest)
For Each objMatch In colMatches
WScript.Echo "RegExp matched " & objMatch.Length & " characters " & chr(34) & objMatch.Value & Chr(34) & _
" beginning at position " & objMatch.FirstIndex
Next
Output:
RegExp matched 4 characters "test" beginning at position 11
If you want to work with the matches, you can use the RegExp object’s Execute method instead. This method returns a collection of Match objects that represent the matches that were found. Each Match object contains three properties that you can use to work with the matched patterns. The length property returns the number of characters matched by the pattern, the Value property returns the text string that was matched, and the FirstIndex property returns an integer representing the string position where the match occurred.
WScript.Echo colMatches.Item(0).Value
WScript.Echo colMatches(0).Value
Output:
test
test
As with any collection, you can access individual objects directly. Here I’m accessing the first match that was found. In the first line, I use standard notation for accessing the collection. Take a close look at the second line though. The Item property is the default property for the Matches collection, so I don’t have to specify it directly. Either syntax is perfectly acceptable.
strTest = "This is my test string."
Set objRegExp = New RegExp
objRegExp.IgnoreCase = True
objRegExp.Pattern = "test"
strNew = objRegExp.Replace(strTest, "new")
WScript.Echo strTest
WScript.Echo strNew
Output:
This is my test string.
This is my new string.
RegExp’s Replace method is used to perform a text replacement based upon pattern matches. The first parameter indicates the text string to search and the second parameter is a string that represents the replacement text.
Next: Constructing Patterns >>
More Windows Scripting Articles
More By Nilpo