RegEx.Replace

From Xojo Documentation

Method

RegEx.Replace(TargetString as String [,SearchStartPosition as Integer]) As String

Supported for all project types and targets.

Finds SearchPattern in TargetString and Replaces the contents of SearchPattern with ReplacementPattern. SearchStartPosition is optional. If not specified, will start from the last SearchStartPosition.


Method

RegEx.Replace() As String

Supported for all project types and targets.

Finds SearchPattern in the last used TargetString and Replaces the contents of SearchPattern with ReplacementPattern starting at the last SearchStartPosition.

Returns the resulting String.

Sample Code

This code does a simple remove of HTML tags from source HTML:

Var re As New RegEx
re.SearchPattern = "<[^<>]+>"
re.ReplacementPattern = ""
re.Options.ReplaceAllMatches = True

Var html As String = "<p>Hello.</p>"
Var plain As String = re.Replace(html)

MessageBox(plain) // "Hello."

This code finds all occurrences of the word "a" and replace them all with "the":

Var re As New RegEx
re.SearchPattern = "\ba\b"
re.ReplacementPattern = "the"
re.Options.ReplaceAllMatches = True

Var origText As String = "a bus drove on a street in a town"
Var newText As String = re.Replace(origText)

MessageBox(newText) // "the bus drove on the street in the town"

This code replaces the second occurrence only:

Var re As New RegEx
re.SearchPattern = "\ba\b"
re.ReplacementPattern = "the"

Var text As String = "a bus drove on a street in a town"

Var match As RegExMatch = re.Search(text)
If match <> Nil Then
text = re.Replace
End If

MessageBox(text) // "a bus drove on the street in a town"

This code uses the same RegEx on several strings:

Var sources() As String = _
Array("<b>this</b>", "<i>that</i>", "<strong>the other</strong>")

Var re As New RegEx
re.SearchPattern = "<[^<>]+>"
re.ReplacementPattern = ""
re.Options.ReplaceAllMatches = True

For sourceIndex As Integer = 0 To sources.Ubound
sources(sourceIndex) = re.Replace(sources(sourceIndex))
Next sourceIndex

// sources now contains
// {"this", "that", "the other"}