Replace text that appears at the end of a string

2019-06-28 03:44发布

问题:

Consider "artikelnr". I want to replace "nr" by "nummer", but when I consider "inrichting", I do NOT want to replace "nr". So I just want to replace "nr" by "nummer" if it's at the end of a word.

回答1:

regex is your friend, here:

sub('nr$', 'nummer', 'artikelnr')
# [1] "artikelnummer"

The $ indicates "end of string", so nr will only be replaced with nummer when it appears at the end of the string.

sub can operate on an entire vector, e.g. for a character vector x, do:

sub('nr$', 'nummer', x)


回答2:

If you don't mind using the stringr package, str_replace is also handy :

library(stringr)
str_replace("artikelnr", "nr$", "nummer")


标签: r string replace