Skip to main content


For a given string, replaces all matches of a regex pattern with a replacement string

replace(searchString, regex, replacement)


  • searchString: The string to search within
  • regex: The regular expression pattern to search in searchString
  • replacement: The string to replace for each match of pattern


  • The replaced string

Using captured matches in replacement string#

If the regex pattern makes use of capture groups, the replacement string can reference the captured values using $ sign. If a named capture group is used, use syntax ${GROUP_NAME}. For unnamed capture groups, use group number like so, ${GROUP_NUMBER}. Following examples shows both the approaches.


  • Using a regex pattern with named capture group

    text = 'Save your $$$. Now get $50 discount on every $500 spent.'# Replace all occurrences of '$xx' to 'USDxx'pattern = '\\$(?<price>[1-9][0-9]{0,4})'replacement = 'USD${price}' # referencing captured value by group nameprint(replaceAll(text, pattern, replacement))# prints, Save your $$$. Now get USD50 discount on every USD500 spent.
  • Using a regex pattern with unnamed capture group

    text = 'Your request #19123 is under process'pattern = '#([1-9][0-9]{4,5})'replacement = 'id: $1' # referencing captured value by group numberprint(replaceAll(text, pattern, replacement))# prints, Your request id: 19123 is under process
  • Using a regex pattern with no groups

    text = 'I will play football with my mates tomorrow'pattern = 'play[\\s\\S]*tomorrow?' # match everything in betweenreplacement = 'play tomorrow'print(replaceAll(text, pattern, replacement))# prints, I will play tomorrow

Read our notes on regular expression to learn about the regex pattern rules.