replaceAll
For a given string
, replaces all matches of a regex pattern with a replacement string
replace(searchString, regex, replacement)
#
ParameterssearchString
: Thestring
to search withinregex
: The regular expression pattern to search insearchString
replacement
: Thestring
to replace for each match of pattern
#
Returns- The replaced
string
#
Using captured matches in replacement stringIf 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.
#
ExamplesUsing 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
info
Read our notes on regular expression to learn about the regex pattern rules.