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.

Syntax
Luau
Regex:Replace(contents: string, replacement: string) -> string

Parameters

Call this method with a Regex receiver. The colon supplies self implicitly; a dot call must pass the receiver explicitly.

Function parameters
ParameterTypeDescription
contentsstringOriginal text.
replacementstringReplacement text in Java Matcher syntax; $1, $2, and so on refer to capture groups.

Returns

string

The 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

Example
Luau
local version = Regex.new("v([0-9]+)")
print(version:Replace("v2 then v3", "version $1")) -- version 2 then v3
Kawaii documentation