StrSubs(s, pattern, replace [, n])
or
string.gsub(s, pattern, replace [, n])
This is a very powerful function and can be used many ways. Used simply, it can replace all instances of the pattern. A pair of values is returned with the modified string and the number of substitutions made. The optional fourth argument n can be used to limit the number of substitutions made.
Option |
Description |
s |
The string on which to perform the replacement. |
pattern |
The pattern to replace. |
replace |
The replacement string. |
n (optional) |
An integer specifying the maximum number of replacements. |
> print(StrSubs("Hello there", "there", "HyperMath user"))
Hello HyperMath user 1
> print(StrSubs("talk and talk", "talk", "walk", 1)) // limit substitutions made to 1
walk and talk 1
The pattern capture, along with character class, can be used for more powerful substitutions. For example, replace all characters inside braces {}.
> print(StrSubs("Replace {this}","{(.-)}", "that" ))// replace all characters inside braces
Replace {that} 1
If a capture is used, this can be referenced in the replacement string using the notation %capture_index. For example:
> print(StrSubs("Jan 31", "(%a*) (%d*)", "%2 %1")) // swaps
31 Jan 2
In the above example, the first capture is indexed as %1 and the second one as %2.