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
See Also
Get VBScript in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.