RegEx.Replace

From Xojo Documentation
Jump to: navigation, search
Method

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

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

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

Returns the resulting String.

Example

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

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

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

MsgBox(plain) // "Hello."

This code will find the first occurrence of the word "a" and replace all subsequent occurrences with "the":

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

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

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

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

This code will replace the second occurrence only:

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

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

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

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

This code will use the same RegEx on several strings:

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

Dim 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"}
Personal tools
Namespaces

Variants
Actions
Main
Content
Starting Out
Dig Deeper
More Help
Toolbox
About