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.
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.
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.
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.
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)
If you don't mind using the stringr
package, str_replace is also handy :
library(stringr)
str_replace("artikelnr", "nr$", "nummer")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With