从字符串中删除特定的最后一个字符 [英] Remove specific last character from string
问题描述
我有以下字符串向量:
EC02 502R 603 515 602
KL07 601 511R 505R 506R 503
508 514 501 509R 510 501R
512R 516 507 604 502 601R
SPK01 504 504R ACK01 503R 508R
507R ACK03 513 EC01 506 ECH01
ACK02 SPK02 509 511 512 505
KA01 RS01 510R SKL01 SPK03 603R
602R 604R 513R AECH01 ER03 AECH02
RS02 514R ER01 RH01 AR05 RH02
515R ER02 M01
我要替换502R to 502, 501R to 501, 503R to 503
,依此类推...
I want to replace 502R to 502, 501R to 501, 503R to 503
and so on...
只有字符R
必须替换,该字符出现在字符串的末尾.
Only character R
has to be replaced which is occurring at the end of the string.
如何使用gsub
做到这一点?
推荐答案
如果您有字符串矢量,并且想要替换其中的最后一个R
字符,则可以使用sub
. $
在这里确保R
是向量中的最后一个字符.
If you have a string vector and want to replace the last R
character from it you can use sub
. $
here ensures that the R
is the last character in your vector.
sub("R$", "", str)
#[1] "EC02" "502" "603" "5RFRS"
数据
str <- c("EC02", "502R","603", "5RFRS)
我在这里使用的是sub
而不是gsub
. sub
仅替换第一次出现的模式,而gsub
替换所有出现的模式,尽管在这种情况下sub
/gsub
的使用无关紧要.
I have used sub
here instead of gsub
. sub
replaces only first occurrence of the pattern whereas gsub
replaces all occurrences of the pattern though in this case the usage of sub
/gsub
wouldn't matter.
这篇关于从字符串中删除特定的最后一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!