RegEx.Replace

From Xojo Documentation

You are currently browsing the old Xojo documentation site. Please visit the new Xojo documentation site!
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 sampleText As String = "a bus drove on a street in a town"

Var match As RegExMatch = re.Search(sampleText) // Find the first SearchPattern in the text
If match <> Nil Then
sampleText = re.Replace // Find the second SearchPattern in the text and replace it
End If

MessageBox(sampleText) // "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"}