Name
RegExp.Replace Method
Syntax
RegExp.Replace(string1, string1)-
string1 Use: Required
Data Subtype: String
The string to be searched.
-
string2 Use: Required
Data Subtype: String
The replacement string.
Return Value
A variant of subtype String containing the entire string that results
when matched substrings in string1 are
replaced with string2.
Description
Performs a regular expression search against
string1 and replaces matched substrings
with string2.
Rules at a Glance
The method searches
string1using the RegExp object’s Pattern property.If no matches are found, the method returns
string1unchanged.
Programming Tips & Gotchas
string2, the replacement string, can
contain pattern strings that control how substrings in
string1 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
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access