Method: Replace for RegExp
- Updated2024-09-12
- 1 minute(s) read
Methods > Method: Replace for RegExp
Method: Replace for RegExp
Replaces the text pattern found in a search with regular expressions.
sReplace = Object.Replace(sourceString, replaceVar)
Object | RegExp Object with this method |
sourceString | String Specifies the character string you want to search through. |
replaceVar | Variant Specifies the text to replace the original text. |
sReplace | String Receives the character string with the replacement. |
The following example specifies the text pattern bc and replaces it in the entire character string:
Dim RegExpression, sText Set RegExpression = CreateObject("VBScript.RegExp") RegExpression.Pattern = "bc" RegExpression.Global = TRUE RegExpression.IgnoreCase = TRUE sText = RegExpression.Replace("abcABC","bcdef") Call MsgBox(sText) ' Returns "abcdefAbcdef"
The following example searches a pattern that consists of one or more alphabetical characters, and saves them as submatch. The second part of the text pattern consists of a reference to this submatch. The text pattern searches double words and replaces them with the submatch. Using $1 in the replace method refers to the first stored submatch:
Dim RegExpression, sText Set RegExpression = CreateObject("VBScript.RegExp") RegExpression.Pattern = "\b([a-z]+) \1\b" RegExpression.Global = TRUE RegExpression.IgnoreCase = TRUE sText = "one one two three three" sText = RegExpression.Replace(sText,"$1") Call MsgBox(sText) ' Returns "one two three"