O'Reilly logo

VBScript in a Nutshell, 2nd Edition by Ron Petrusha, Matt Childs, Paul Lomax

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Name

RegExp.Replace Method

Syntax

RegExp.Replace(searchString, replaceString)
searchString

Use: Required

Data Type: String

The string to be searched.

replaceString

Use: Required

Data Type: String

The replacement string.

Return Value

A String containing the entire string that results when matched substrings in searchString are replaced with replaceString.

Description

Performs a regular expression search against searchString and replaces matched substrings with replaceString.

Rules at a Glance

  • The method searches searchString using the RegExp object’s Pattern property.

  • If no matches are found, the method returns searchString unchanged.

Programming Tips and Gotchas

replaceString the replacement string, can contain pattern strings that control how substrings in searchString should be replaced.

Example

The following WSH code illustrates the use of subexpressions in the search and replacement strings. The search returns three subexpressions: “to be”, “or”, and “not to be”. The first subexpression is replaced with the third, while the third subexpression is replaced with the first, resulting in the string “not to be or to be”:

Dim strString, strPattern, strReplace, strResult
Dim oRegExp

strString = "to be or not to be " 
strPattern = "(\S+\s+\S+\s+)(\S+\s+)(\S+\s+\S+\s+\S+\s+)"
strReplace = "$3$2$1"

Set oRegExp = New RegExp
oRegExp.Pattern = strPattern

strResult = oRegExp.Replace(strString, strReplace)
If strResult = strString Then
   MsgBox "No replacements were made"
Else
   MsgBox strResult
End If

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required