Regex: Replace Synchronous
Replace the first match of a compiled pattern and return a new string. It is useful for a targeted edit, such as rewriting one prefix while preserving the rest of a line.
Luau
Regex:Replace(contents: string, replacement: string) -> stringParameters
Call this method with a Regex receiver. The colon supplies self implicitly; a dot call must pass the receiver explicitly.
| Parameter | Type | Description |
|---|---|---|
contents | string | Original text. |
replacement | string | Replacement text in Java Matcher syntax; $1, $2, and so on refer to capture groups. |
Returns
stringThe text after the first replacement, or the unchanged original text if there was no match.
Usage notes
This implementation uses replaceFirst. It does not replace every occurrence. Escape replacement punctuation according to Java Matcher rules when it must be literal.
Example
Luau
local version = Regex.new("v([0-9]+)")
print(version:Replace("v2 then v3", "version $1")) -- version 2 then v3