[R] String replace

Ivan Krylov kry|ov@r00t @end|ng |rom gm@||@com
Wed Apr 3 19:38:35 CEST 2019


On Wed, 3 Apr 2019 15:01:37 +0100
Graham Leask via R-help <r-help using r-project.org> wrote:

Suppose that `BHC$Date` contains a string "M_24".

You do:

> BHC <-BHC %>% mutate ( Date = stringr :: str_replace ( Date , "M_2" ,
> "01-04-2017"))

before you have a chance to do:

> BHC <-BHC %>% mutate ( Date = stringr :: str_replace ( Date ,
> "M_24" , "01-02-2019"))

So now it has "01-04-20174" because the first expression had a
successful match and already made a replacement.

help() for stringi::stringi-search-regex says that look-around
expressions are supported, so one of the ways to prevent this would be
to modify your patterns to look like e.g. 'M_2(?!\\d)' to match
'M_2' that is *not* followed by a digit.

-- 
Best regards,
Ivan



More information about the R-help mailing list