Skip to main content

Text.replace

replacetermreplacementcase_sensitivityonly_first

Group: Text
Aliases: replace text

Documentation

Perform a text or regex replace. Returns the text with all matched elements replaced by the provided replacement. If input is empty, the function returns the input 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 For details on Enso's Regex syntax, see the Help Documentation.

Arguments

  • term: The Text or Regex to find.
  • replacement: The text to replace matches with.
  • case_sensitivity: Specifies if the text values should be compared case sensitively.
  • only_first: If True, only replace the first match.

Examples

Replace letters in the text "aaa".

      'aaa'.replace 'aa' 'b' == 'ba'

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

      "Hello World!".replace "[lo]".to_regex "#" == "He### W#r#d!"

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

      "Hello World!".replace "l" "#" only_first=True == "He#lo World!"

Replace texts in quotes with parentheses.

       '"abc" foo "bar" baz'.replace '"(.*?)"'.to_regex '($1)' == '(abc) foo (bar) baz'

Extended partial matches in case-insensitive mode.

      # The ß symbol matches the letter `S` twice in case-insensitive mode, because it folds to `ss`.
'ß'.replace 'S' 'A' case_sensitivity=Case_Sensitivity.Insensitive . should_equal 'AA'
# The 'ffi' ligature is a single grapheme cluster, so even if just a part of it is matched, the whole grapheme is replaced.
'affib'.replace 'i' 'X' case_sensitivity=Case_Sensitivity.Insensitive . should_equal 'aXb'

Regexp replace.

      '<a href="url">content</a>'.replace '<a href="(.*?)">(.*?)</a>'.to_regex '$2 is at $1'== 'content is at url'

Errors

  • If an empty regex is used, find throws an Illegal_Argument error.
  • If a non-default locale is used, find throws an Illegal_Argument error.

Remarks

Matching Grapheme Clusters

In case-insensitive mode, a single character can match multiple characters, for example ß will match ss and SS, and the ligature will match ffi or f etc. Thus in this mode, it is sometimes possible for a term to match only a part of some single grapheme cluster, for example in the text ffia the term ia will match just one-third of the first grapheme . Since we do not have the resolution to distinguish such partial matches, a match which matched just a part of some grapheme cluster is extended and treated as if it matched the whole grapheme cluster. Thus the whole grapheme cluster may be replaced with the replacement text even if just a part of it was matched.