Replace text that appears at the end of a string

坚强是说给别人听的谎言 提交于 2020-01-03 17:45:31

问题


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")


来源:https://stackoverflow.com/questions/26547186/replace-text-that-appears-at-the-end-of-a-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!