Somacon.com: Articles on websites & etc.

§ Home > Index > ASP Programming

VBScript Regular Expression Functions

Here is the VBScript Replace Function Documentation at Microsoft.com, for simple search and replace.

For advanced search and replace, Microsoft Visual Basic Scripting Edition version 5+ contains limited regular expression support. You can use these little utility functions to perform common regular expression tasks, such as finding the first match in a string, or replacing all matches with another string. VBScript 5 is included with Windows Script Host, Microsoft Internet Explorer 5+, Microsoft Internet Information Services 5.0+, and Microsoft Visual Studio .NET.

VBScript Find First Match By Regular Expression Utility Function


' Get the first regex submatch from the string
' Returns empty string if not found, otherwise returns the matched string
Function GetFirstMatch(PatternToMatch, StringToSearch)
	Dim regEx, CurrentMatch, CurrentMatches

	Set regEx = New RegExp
	regEx.Pattern = PatternToMatch
	regEx.IgnoreCase = True
	regEx.Global = True
	regEx.MultiLine = True
	Set CurrentMatches = regEx.Execute(StringToSearch)

	GetFirstMatch = ""
	If CurrentMatches.Count >= 1 Then
		Set CurrentMatch = CurrentMatches(0)
		If CurrentMatch.SubMatches.Count >= 1 Then
			GetFirstMatch = CurrentMatch.SubMatches(0)
		End If
	End If
	Set regEx = Nothing
End Function

' Example
' Parse out the database name from a SQL server database connection string
Function GetDatabaseName(ByVal DSNString)
	GetDatabaseName = GetFirstMatch(".*Initial Catalog=(.*);", DSNString)
End Function

VBScript Replace All Matches By Regular Expression Utility Function


' Replace all matches in the string with the replacement text
Sub ReplaceAllByExpression(ByRef StringToExtract, ByVal MatchPattern, _
	ByVal ReplacementText)
	Dim regEx, CurrentMatch, CurrentMatches

	Set regEx = New RegExp
	regEx.Pattern = MatchPattern
	regEx.IgnoreCase = True
	regEx.Global = True
	regEx.MultiLine = True
	StringToExtract = regEx.Replace(StringToExtract, ReplacementText)
	Set regEx = Nothing

End Sub

' Example
' Remove all images from an HTML page
ReplaceAllByExpression HTMLPageData, "<img[^<]*?>", ""


Created 2005-02-07, Last Modified 2011-07-24, © Shailesh N. Humbad
Disclaimer: This content is provided as-is. The information may be incorrect.