如果满足条件,则替换字符串的最后一个字符

Replace last characters of a string if it meets criteria

我有一个字符串向量:

asdf <- c("a^sdf^", "asdf^^")

现在我想删除两个字符串的最后一个元素,但前提是最后一个元素是 ^,导致:

[1] "a^sdf"  "asdf"

我试过了:

function1 <- function(x){
  while(any(substr(x, nchar(x) - 1 + 1, nchar(x)) == "^")){
    x <- gsub(".{1}$", "", x)
  }
  return(x)
}
function1(asdf)
[1] "a^sd"  "asdf"

如您所见,第一个字符串在末尾减少为 ^ 以上。我尝试将 if 条件与 while 循环结合使用,但没有成功。缺少什么以便只有 ^ 被删除?

一个可能的解决方案,使用stringr::str_remove

library(stringr)

str_remove(asdf, "\^+$")

#> [1] "a^sdf" "asdf"

我们可以把它们看成一个空格,然后使用base trimws - trim whitespace:

trimws(asdf, which = "right", whitespace = "\^")
# [1] "a^sdf" "asdf"