Home > Enterprise >  Replace last characters of a string if it meets criteria
Replace last characters of a string if it meets criteria

Time:01-06

I have a vector of strings:

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

Now i want to remove the last element of both strings, but only if that last element is a ^, resulting in:

[1] "a^sdf"  "asdf"

I tried:

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"

As you can see the first string is reduced to more than ^ at the end. I tried experimenting with if conditions in combination to the while loop but it didn't work out. What is missing so that only the ^ gets removed?

CodePudding user response:

A possible solution, using stringr::str_remove:

library(stringr)

str_remove(asdf, "\\^ $")

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

CodePudding user response:

We can think of them as a whitespace and use base trimws - trim whitespace:

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