替换出现在字符串末尾的文本 [英] Replace text that appears at the end of a string

查看:42
本文介绍了替换出现在字符串末尾的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑"artikelnr".我想用 "nummer" 替换 "nr",但是当我考虑 "inrichting" 时,我不想替换 nr".所以我只想用 "nummer" 替换 "nr" 如果它在单词的末尾.

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.

推荐答案

regex 是你的朋友,在这里:

regex is your friend, here:

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

$表示字符串结束",所以nr只有出现在字符串末尾时才会被替换为nummer.

The $ indicates "end of string", so nr will only be replaced with nummer when it appears at the end of the string.

sub 可以对整个向量进行操作,例如对于字符向量 x,执行:

sub can operate on an entire vector, e.g. for a character vector x, do:

sub('nr$', 'nummer', x)

这篇关于替换出现在字符串末尾的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆