I have a string, in which I'm trying to replace the first matching pattern with a corresponding replacement. EG in my example below : if bb
is found first, replace it by foo
and don't replace anything else, but if cc
is found first, replace it by bar
and don't replace anything else.
This behaves almost as desired, except the replacement
argument is not interpreted as a regex, but as a whole string. (But the pattern
argument is seen as a regex, as required).
stri_replace_first_regex(
c(" bb cc bb cc "," cc bb cc bb ", " aa bb cc "),
pattern = " bb | cc ",
replacement = " foo | bar ")
Ouputs : " foo | bar cc bb cc " " foo | bar bb cc bb " " aa foo | bar cc "
while I want it to output " foo cc bb cc " " bar bb cc bb" " aa foo cc "
Any idea on how to solve that ?
Thanks.
More context :
My inputs can have basically almost any formatting, they are postal adresses entered by customers, in which I need to replace the type of street by something standardized (for instance, turn street
into st
, road
in rd
and avenue
in av
). Any of those words can appear again (eg 20 bis road of sesame street
), so I consider only the first appearance as valid, and the subsequent appearances of a word from the pattern
list must not be replaced.