Skip to main content

Regex.replace

replaceinput replacement only_first

Group: Text

Documentation

Replace all occurrences of the pattern described by self in the input with the specified replacement. If this method performs no replacements it will return the input text unchanged. The replacement string can contain references to groups matched by the regex. The following syntaxes are supported: $0: the entire match string $&: the entire match string $n: the nth group $<foo>: Named group foo

Arguments

  • input: The text in which to perform the replacement(s).
  • replacement: The literal text with which to replace any matches.
  • only_first: If True, only replace the first match.

Examples

Replace letters in the text "aa".

      pattern = Regex.compile 'aa'
pattern.replace 'aaa' 'b' == 'ba'

Replace all occurrences of letters 'l' and 'o' with '#'.

       pattern = Regex.compile '[lo]'
pattern.replace 'Hello World!' '#' == 'He### W#r#d!'

Replace the first occurrence of letter 'l' with '#'.

      pattern = Regex.compile 'l'
pattern.replace 'Hello World!' '#' only_first=True == 'He#lo World!'

Replace texts in quotes with parentheses.

       pattern = Regex.compile '"(.*?)"'
pattern.replace '"abc" foo "bar" baz' '($1)' == '(abc) foo (bar) baz'

Replace a literal string with a replacement value.

      pattern = Regex.compile "aa"
input = "aa ab aa ac ad aa aa ax"s
match = pattern.replace input "xyz"
match == "xyz ab xyz ac ad xyz xyz ax"

Replace each word with the same word surrounded by [].

      pattern = Regex.compile "([a-z]+)"
pattern.replace "foo bar, baz" "[$1]" == "[foo] [bar], [baz]"