replaceRegexMatches
replaceRegexMatches(text: String, regex: Regex<T>, replacement: String) : String
Replaces every match of regex in text with replacement.
-
replacementmay reference group captures by name such as${name}or by index such as$3(without braces!) -
If the index is out of bounds, the query terminates with an error.
- The index
$0references the entire matched substring.
- The index
-
If the dereference does not refer to any named group in
regex, the query terminates with an error.- If the dereference name refers to a named group that occurs multiple locations, then the query terminates with an error advising the use of a positional index reference.
-
To embed a literal
$, use"\\$"with string escapes.- The escape is only necessary when
$is followed by a digit, but it is always allowed. - Only
$and\need escaping, but any character can be escaped.
- The escape is only necessary when
-
References to a non-matched group are allowed and are replaced with
"".- For example,
replaceRegexMatches("1234", re`(\d)|(\w)`, "a$2")results in"aaaa".
- For example,
Examples
text | regex | replacement | Result |
|---|---|---|---|
"hello world" | re`(?<word>\w+)` | "_$1_" | "_hello_ _world_" |
"hello world" | re`(?<word>\w+)` | "_$2_" | null (Index out of bounds) |
"hello world" | re`(?<word>\w+)` | "$0$0" | "hellohello worldworld" |
"abc123def456" | re`(?<number:Number>\d+)` | "" | "abcdef" |
"I have 2 apples and 13.582 bananas" | re`(?<count:Float>\d+(?:\.\d+)?)` | "<em>$1</em>" | "I have <em>2</em> apples and <em>13.582</em> bananas" |
"A1 B2 C3" | re`(?<letter:String>\w)(?<digit:Number>\d)` | "$2$1" | "1A 2B 3C" |
"12/05/2024 and 20/08/1991 but not 02/01/1974" | re`(?<day:Number>\d{2})/(?<month:Number>\d{2})/(?<year:Number>\d{4})` | "$2 in $3" | "05 in 2024 and 08 in 1991 but not 01 in 1974" |
"Me: jim@place.com, You: timothy@hilltop.school" | re`(?<local>\w+)@(?<domain>\w+)\.(?<tld>\w+)` | "$3" | "Me: com, You: school" |
"Contact me at 555-123-4567 or 444-987-6543" | re`(?<area>\d{3})-(?<exchange>\d{3})-(?<station>\d{4})` | "$2-$1-$3" | "Contact me at 123-555-4567 or 987-444-6543" |
"I have 10 dollars, and you have 5" | re`(?<money:Number>\d+)` | "$$1" | "I have $10 dollars, and you have $5" |
"I have 10 dollars, and you have 5" | re`(?<money:Float>\d+)` | "$1$" | "I have 10$ dollars, and you have 5$" |
"I have 10 dollars, and you have 5" | re`(?<money:String>\d+)` | "$$" | "I have $$ dollars, and you have $$" |
"I have 10 dollars, and you have 5" | re`(?<money:String>\d+)` | "$" | "I have $ dollars, and you have $" |
"I have 10 dollars, and you have 5" | re`(?<money:String>\d+)` | "\\$25" | "I have $25 dollars, and you have $25" |
"I have 10 dollars, and you have 5" | re`(?<money:String>\d+)` | "$25" | null (Index out of bounds) |
See also
Functions
- match: Gets a record of information about text that matches the structure specified by a regex,
or otherwise
null. - regexMatches: Gets the list of all substring matches of a given regex.