Jumat, 29 November 2024

Regular Expression Programming (Scripting)

 

Regular Expression Programming (Scripting)

Windows Scripting 5.8

Updated: August 2009

You can use regular expressions in JScript and Visual Basic Scripting Edition (VBScript) to search for patterns in a string, replace text, and extract substrings.

The following JScript example finds all occurrences of a word.

The statement that creates the regular expression is

var re = /\w+/g;

The /\w+/ pattern specifies to match one or more of any of the following characters: A-Z, a-z, 0-9, and the underscore character. The "g" (global) flag that follows the pattern specifies that the search should find all occurrences of the pattern instead of just the first occurrence.

You can also use the following alternative JScript syntax.

var re = new RegExp("\\w+", "g");

To retrieve each match, the exec Method (Windows Scripting - JScript) keeps searching, starting at the position of lastIndex, until null is returned.

No code example is currently available or this language may not be supported.

The following JScript example finds just the first match. Because the global (g) flag is not set, the search starts from the start of the search string.

No code example is currently available or this language may not be supported.

The following VBScript example finds all occurrences of a word.

The "\w+" regular expression pattern specifies to match one or more of any of the following characters: A-Z, a-z, 0-9, and the underscore character.

Setting the Global property to True specifies that the search should find all occurrences of the pattern instead of just the first occurrence.

The Execute Method returns a Matches Collection that contains the search results. The program iterates through the Matches collection to retrieve each match.

Sub SearchGlobal
    Dim src, ptrn, re, Match, Matches

    src = "The quick brown fox jumps over the lazy dog"
    ptrn = "\w+"

    ' Create the regular expression.
    Set re = New RegExp
    re.Pattern = ptrn
    re.IgnoreCase = False
    re.Global = True

    ' Perform the search.
    Set Matches = re.Execute(src)

    ' Iterate through the Matches collection.
    For Each Match in Matches
        ' New line.
        document.write ("<br />")

        document.write (Match.FirstIndex & " ")
        document.write (Match.Value)
    Next

    ' Output:
    '  0 The
    '  4 quick
    '  10 brown
    '  16 fox
    '  20 jumps
    '  26 over
    '  31 the
    '  35 lazy
    '  40 dog
End Sub

The following VBScript example finds a single occurrence of a match.

Sub SearchNonGlobal
    Dim src, ptrn, re, Match, Matches

    src = "The quick brown fox jumps over the lazy dog"
    ptrn = "\w+"

    ' Create the regular expression.
    Set re = New RegExp
    re.Pattern = ptrn
    re.IgnoreCase = False
    re.Global = False

    ' Perform the search.
    Set Matches = re.Execute(src)

    If Matches.Count = 0 Then
        document.write ("Not Found")
    Else
        ' New line.
        document.write ("<br />")

        document.write (Matches(0).FirstIndex & " ")
        document.write (Matches(0).Value)
    End If

    ' Output:
    '  0 The
End Sub

In the following examples, occurrences of "the" are replaced with "a". The instance of "The" is not replaced, because the i (ignore case) flag is not included in the regular expression flags.

The JScript example uses the replace Method (Windows Scripting - JScript).

No code example is currently available or this language may not be supported.

The VBScript example uses the Replace Method (VBScript).

Sub ReplaceGlobal
    Dim src, ptrn, re, Result

    src = "The batter hit the ball with the bat "
    src = src & "and the fielder caught the ball with the glove."

    ptrn = "the"

    ' Create the regular expression.
    Set re = New RegExp
    re.Pattern = ptrn
    re.IgnoreCase = False
    re.Global = True

    ' Replace "the" with "a".
    Result = re.Replace(src, "a")

    document.write(Result)

    ' Output:
    '  The batter hit a ball with a bat and a fielder caught a ball with a glove. 
End Sub

Placing parentheses in a regular expression pattern creates a submatch that can be stored for later use.

In the following example, the pattern includes three submatches. The submatch strings display together with each match.

For the JScript example, an array is returned by the exec Method (Windows Scripting - JScript). Element zero of the array contains the complete match, and the elements 1 through n contain the submatches.

No code example is currently available or this language may not be supported.

In this VBScript example, the submatches are contained in the SubMatches Collection of each Match Object.

Function SearchWithSubmatches()
    Dim src, ptrn, re, Match, Matches, NewLine, s

    src = "Please send mail to george@contoso.com and someone@example.com. Thanks!"

    ' Set the pattern to search for an e-mail address.
    ' (More sophisticated RegExp patterns are available for
    '  matching an email address).
    ptrn = "(\w+)@(\w+)\.(\w+)"

    ' Create the regular expression.
    Set re = New RegExp
    re.Pattern = ptrn
    re.Global = True

    ' Get the Matches collection
    Set Matches = re.Execute(src)

    ' Create the output string.
    NewLine = "<br />"
    s = ""

    For Each Match in Matches
        s = s & NewLine

        ' The Match object contains the entire match.
        s = s & "e-mail address: " & Match.Value

        ' Get the submatched parts of the address.
        s = s & NewLine
        s = s & "user name: " & Match.SubMatches(0)
        s = s & NewLine
        s = s & "host name: " & Match.SubMatches(1)
        s = s & NewLine
        s = s & "top-level domain: " & Match.SubMatches(2)
        s = s & NewLine
    Next

    document.write (s)

    ' Output:
    '  e-mail address: george@contoso.com
    '  user name: george
    '  host name: contoso
    '  top-level domain: com

    '  e-mail address: someone@example.com
    '  user name: someone
    '  host name: example
    '  top-level domain: com
End Function

In the JScript regular expression /abc/gim, the g specifies the global flag, the i specifies the ignore case flag, and the m specifies the multiline flag.

In VBScript, you can specify these flags by setting the equivalent properties to True.

The following table shows the allowed flags.

JScript flag

VBScript property

If flag is present or property is True

g

Global

Find all occurrences of the pattern in the searched string instead of just the first occurrence.

i

IgnoreCase

The search is case-insensitive.

m

Multiline

^ matches positions following a \n or \r, and

$ matches positions before \n or \r.

Whether or not the flag is present or the property is True, ^ matches the position at the start of the searched string, and $ matches the position at the end of the searched string.

The following additional programming features are available.

Feature

Description

compile Method (Windows Scripting - JScript)

Compile a regular expression into an internal format for faster execution.

test Method (Windows Scripting - JScript) and Test Method (VBScript)

Test whether a pattern occurs in a searched string.

search Method (Windows Scripting - JScript)

Return the position of the first match.

Date

History

Reason

August 2009

Added topic.

Customer feedback.

Community Content Add

Tidak ada komentar: