Replace the text that appears at the end of the line

Consider "artikelnr". I want to replace "nr"with "nummer", but when I review "inrichting", I DO NOT want to replace "nr". So I just want to replace "nr"with "nummer"if it is at the end of a word.

+2
source share
2 answers

regex - your friend, here:

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

$indicates "end of line", therefore nris replaced only by nummerwhen it appears at the end of the line.

subcan work on the whole vector, for example. for a character vector x, do:

sub('nr$', 'nummer', x)
+7
source

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

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

All Articles