Skip to main content

replaceFirst

For a given string, replaces only the first match of a regex pattern with a replacement string

replaceFirst(searchString, regex, replacement)

Parameters#

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

Returns#

  • 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.

Examples#

  • 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(replaceFirst(text, pattern, replacement))# prints, Save your $$$. Now get USD50 discount on every $500 spent.
  • Using a regex pattern with unnamed capture group

    text = 'Your request #19123 and order #873645 has been taken'pattern = '#([1-9][0-9]{4,5})'replacement = 'id: $1' # referencing captured value by group numberprint(replaceFirst(text, pattern, replacement))# prints, Your request id: 19123 and order #873645 has been taken
  • Using a regex pattern with no groups

    text = `I will play football with my mates tomorrowlet's play around noon tomorrow`pattern = 'play.*?tomorrow?' # match everything in betweenreplacement = 'play tomorrow'print(replaceFirst(text, pattern, replacement))/*I will play tomorrow  let's play around noon tomorrow*/
info

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