web analytics

Using Regular Expressions in VBScript

Options

davegate 143 - 921
@2016-01-17 10:57:42

VBScript has built-in support for regular expressions. You can use regular expressions in VBScript by creating one or more instances of the RegExp object which has only four properties and three methods. This object allows you to find regular expression matches in strings, and replace regex matches in strings with other strings.

After creating the object, assign the regular expression you want to search for to the Pattern property. If you want to use a literal regular expression rather than a user-supplied one, simply put the regular expression in a double-quoted string.

By default, the regular expression is case sensitive. Set the IgnoreCase property to True to make it case insensitive.

The caret(^) and dollar($) only match at the very start and very end of the subject string by default. If your subject string consists of multiple lines separated by line breaks, you can make the caret and dollar match at the start and the end of those lines by setting the Multiline property to True. VBScript does not have an option to make the dot match line break characters.

Finally, if you want the RegExp object to return or replace all matches instead of just the first one, set the Global property to True.

'Prepare a regular expression object
Set myRegExp = New RegExp
myRegExp.Pattern = "regex"
myRegExp.IgnoreCase = True
myRegExp.Global = True

After setting the RegExp object's properties, you can invoke one of the three methods to perform one of three basic tasks.

The Test method takes one parameter: a string to test the regular expression on. Test returns True or False, indicating if the regular expression matches (part of) the string. When validating user input, you'll typically want to check if the entire string matches the regular expression. To do so, put a caret at the start of the regex, and a dollar at the end, to anchor the regex at the start and end of the subject string.

The Execute method also takes one string parameter. Instead of returning True or False, it returns a MatchCollection object. If the regex could not match the subject string at all, MatchCollection.Count will be zero. If the RegExp.Global property is False (the default), MatchCollection will contain only the first match. If RegExp.Global is true, Matches> will contain all matches.

The Replace method takes two string parameters. The first parameter is the subject string, while the second parameter is the replacement text. If the RegExp.Global property is False (the default), Replace will return the subject string with the first regex match (if any) substituted with the replacement text. If RegExp.Global is true, Replace will return the subject string with all regex matches replaced.

@2016-01-17 11:26:55

Example 1: Create Contain() function by using RegEx.Test function

The following vbscript code shows you how to create a function named Contain by using RegEx.Test function. This function accepts a string, pattern, and case sensitivity choice to indicate whether or not you would like to ignore the case of letters, it will return TRUE if the string contains the pattern, or FALSE if not.

' Function matches pattern, returns true or false
' varIgnoreCase must be TRUE (match is case insensitive) or FALSE (match is case sensitive)

function Contain(strOriginalString, strPattern, varIgnoreCase)
    set objRegExp = new RegExp
    objRegExp .Pattern = strPattern
    objRegExp .IgnoreCase = varIgnoreCase
    objRegExp .Global = True

    Contain = objRegExp.test(strOriginalString)

    set objRegExp = nothing

end function

 

The following code demostrates how to use Contain() function:

Dim has

has = Contain("vbscript', "This demo shows you how to use regular expressions in vbscript.", true);

@2016-01-17 11:50:06

Example 2: Create ParseInt() function by using RegEx.Execute function

The following vbscript code shows you how to create a function named ParseInt by using RegEx.Execute function. This function accepts a string and extracts last number from the string.

' Function ParseInt extracts numbers from a string.
' Returns only the *last* match found
'         (or, with objRE.Global = False, only the *first* match)

Function ParseInt( myString )

    Dim colMatches, objMatch, objRE, strPattern

    ' Default if no numbers are found
    ParseInt = 0

    strPattern = "[-+0-9]+"       ' Numbers positive and negative; 
    Set objRE = New RegExp        ' Create regular expression object.
    objRE.Pattern    = strPattern ' Set pattern.
    objRE.IgnoreCase = True       ' Set case insensitivity.
    objRE.Global     = True       ' Set global applicability:
                                  '   True  => return last match only,
                                  '   False => return first match only.
    Set colMatches = objRE.Execute( myString )  ' Execute search.
    For Each objMatch In colMatches             ' Iterate Matches collection.
        ParseInt = objMatch.Value
    Next

    Set objRE = Nothing

End Function

 

The following code demostrates how to use Val() function:

Dim abc
     
abc = Val("20056 hgghghgh gghgh 445")

'455
@2016-01-17 12:29:06

Example 3: Create Replace() function by using RegEx.Replace function

The following vbscript code shows you how to create a function named Replace by using RegEx.Replace function. This function accepts a source string, a pattern, a replacement string and case sensitivity choice. It will replace all instances of the pattern with the replacement in the string (if you change ".Global = True" to ".Global = False" then the function will only replace the first instance of the pattern with the replacement).

' Function replaces pattern with replacement
' varIgnoreCase must be TRUE (match is case insensitive) or FALSE (match is case sensitive)
function Replace(strOriginalString, strPattern, strReplacement, varIgnoreCase)

    set objRegExp = new RegExp
    objRegExp.Pattern = strPattern
    objRegExp.IgnoreCase = varIgnoreCase
    objRegExp.Global = True

    Replace = objRegExp.replace(strOriginalString, strReplacement)
 
    set objRegExp = nothing
 
end function

 

The following code demostrates how to use Contain() function to convert fake phone number 410-1234567 to (410)1234567:

WScript.Echo Replace("410-1234567", "^([0-9]{2, 3})-([0-9]{7})$", "($1)$2", True)

Comments

You must Sign In to comment on this topic.


© 2024 Digcode.com