VBS tutorial: objects – regular expression (regexp) objects


Regular expression (regexp) object
Provides simple regular expression support.

The following code illustrates the usage of regexp object:

Function RegExpTest(patrn, strng)
 Dim regex, match, matches' create variables.
 Set regex = new regexp 'establish a regular expression.
 Regex. Pattern = pattern 'sets the pattern.
 Regex.ignorecase = true 'sets whether characters are case sensitive.
 Regex. Global = true 'set global availability.
 Set matches = regex. Execute (strng) 'performs a search.
 For each match in matches' traverse the matching set.
  RetStr = RetStr & "Match found at position "
  RetStr = RetStr & Match.FirstIndex & ". Match Value is '"
  RetStr = RetStr & Match.Value & "'." & vbCRLF
 RegExpTest = RetStr
End Function
MsgBox(RegExpTest("is.", "IS1 is2 IS3 is4"))

Regexp object provides regular expression support in VBScript. The object has 3 properties and 3 methods.

1) Execute method

This method is used to detect the match of the specified regular expression, and its value returns a matches collection, which contains all match objects detected to match. If no match is detected, an empty matches collection is returned.

Syntax format: regexp. Execute (string)
Where regexp is the variable name of regexp object; String is a valid string expression for match detection.

2) Replace method

When the replace method is called, if a character (string) matching the specified regular expression is found in the specified string, it will be replaced with the specified other character (string). The return value of this method is the string expression after replacement.

Syntax format: regexp.replace (string1, string2)
Where regexp is the variable name of regexp object; String1 is the string expression to be detected and replaced; String2 is a string expression for substitution.

sub window_onLoad()
  dim str,regexp
dim msgstr
str="How are you"

Msgstr = "before replacement:" & STR & "< br / >"
'// create regexp object
set regexp=new RegExp
'// set regular expression

'// set whether to replace all matches
document.write msgstr
'// replace operation

Msgstr = "after replacement:" & msgstr
document.write msgstr
end sub

3) Test method

This method is used to judge whether the specified string matches the specified regular expression. If yes, return to ture; Otherwise, false is returned. Similar to the replace method, when this method is called, the regular expression is specified by the pattern attribute. The difference is that the setting of the global attribute has no effect on this method.

sub window_onLoad()
  dim str,regexp
dim blvar
str="This is a test"

'// create regexp object
set regexp=new RegExp
'// set regular expression

'// call test method
if blvar then
 Document.write "found and in" & STR & " ® Exp.pattern & "matched content"

 Document.write "no match found"  
end if
end sub

This article is introduced here. Friends in need can refer to it.