仅删除出现在字符串末尾的字符串
Remove character string only if it occurs at the end of a string
如果字符串末尾存在最后一个字符“txt”,我想删除它们。但是,有时也可以在字符串的其他位置找到这些字符。
即我想从 "/some-text-here/txt"
中删除 txt
而不是从 "/txt-not-to-remove-text/"
中删除,因为在最后一个示例中它不会在 /
的最后一次出现之后发生
所以,我只想提取出现在字符串末尾的 txt
。
string = c("/some-text-here/txt",
"/some-other-text-here/txt",
"/txt-not-to-remove-text/",
"/txt-another-line-of-text/txt")
我们可以用trimws
trimws(string, whitespace = "/txt", which = 'right')
-输出
[1] "/some-text-here" "/some-other-text-here"
[3] "/txt-not-to-remove-text/" "/txt-another-line-of-text"
或使用 sub
并指定字符串的结尾 ($
)
sub("/txt$", "", string)
如果字符串末尾存在最后一个字符“txt”,我想删除它们。但是,有时也可以在字符串的其他位置找到这些字符。
即我想从 "/some-text-here/txt"
中删除 txt
而不是从 "/txt-not-to-remove-text/"
中删除,因为在最后一个示例中它不会在 /
所以,我只想提取出现在字符串末尾的 txt
。
string = c("/some-text-here/txt",
"/some-other-text-here/txt",
"/txt-not-to-remove-text/",
"/txt-another-line-of-text/txt")
我们可以用trimws
trimws(string, whitespace = "/txt", which = 'right')
-输出
[1] "/some-text-here" "/some-other-text-here"
[3] "/txt-not-to-remove-text/" "/txt-another-line-of-text"
或使用 sub
并指定字符串的结尾 ($
)
sub("/txt$", "", string)