Anita
Anita

Reputation: 789

Replace text that appears at the end of a string

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.

Upvotes: 10

Views: 8649

Answers (2)

Yorgos
Yorgos

Reputation: 30485

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

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

Upvotes: 4

jbaums
jbaums

Reputation: 27408

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)

Upvotes: 23

Related Questions