String to search.
Regular expression pattern.
Replacement string format.
Regular expression attributes.
the resulting string
Replace the letters 'a' with the letters 'ZZ'.
s = "Strap a rocket engine on a chicken." sub(s, "a", "ZZ") // result: StrZZp a rocket engine on a chicken. sub(s, "a", "ZZ", "g") // result: StrZZp ZZ rocket engine on ZZ chicken.
The replacement format can reference the matches using the $&, $$, $', $`, $0 .. $99 notation:
sub(s, "[ar]", "[$&]", "g") // result: St[r][a]p [a] [r]ocket engine on [a] chi
Search string for matches with regular expression pattern with attributes. Replace each match with string generated from format.