Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace text that appears at the end of a string

Tags:

string

replace

r

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.

like image 797
Anita Avatar asked Oct 24 '14 11:10

Anita


People also ask

How do I change the end of a string?

Replace the last character in a String using replace() # Use the String. replace() method to replace the last character in a string, e.g. const replaced = str.

How do you replace a part of a string with another string?

To replace one string with another string using Java Regular Expressions, we need to use the replaceAll() method. The replaceAll() method returns a String replacing all the character sequence matching the regular expression and String after replacement.

How do you replace a word in a string with the index?

You can replace multiple characters in the given string with the new character using the string indexes. For this approach, you can make use of for loop to iterate through a string and find the given indexes. Later, the slicing method is used to replace the old character with the new character and get the final output.


2 Answers

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)
like image 138
jbaums Avatar answered Oct 14 '22 05:10

jbaums


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

library(stringr)
str_replace("artikelnr", "nr$", "nummer")
like image 21
George Dontas Avatar answered Oct 14 '22 05:10

George Dontas