I would like to check if a string ends with a whitespace. If it doesn't I would like to add a trailing space character to the end of the string.
Actually, I check if the string ends with a whitespace with grepl
and then I paste
a space at the end.
append_space <- function(x) {
if(!grepl("(\\s)$", x))
x <- paste0(x, " ")
return(x)
}
However, I think I can do that directly with the sub
function, with a negative lookahead using !
but I don't know how to use it.
Does anyone know how I can do it with sub
?
You can use sub
with capturing group and a backreference in the replacement part:
sub("(\\S)$", "\\1 ", x)
\S
means non-whitespace
.
See demo
You may also try
sub(' ?$', ' ', x)
#[1] "blabla1 " "blabla2 "
where
x <- c("blabla1 ", "blabla2")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With