Name
RegExp.Replace Method
Syntax
RegExp.Replace(searchString, replaceString)searchStringUse: Required
Data Type: String
The string to be searched.
replaceStringUse: 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
searchStringusing the RegExp object’s Pattern property.If no matches are found, the method returns
searchStringunchanged.
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
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