Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determine if string ends in whitespace and append a space if not

Tags:

regex

r

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?

like image 628
Julien Navarre Avatar asked May 06 '15 14:05

Julien Navarre


2 Answers

You can use sub with capturing group and a backreference in the replacement part:

sub("(\\S)$", "\\1 ", x)

\S means non-whitespace.

See demo

like image 135
Wiktor Stribiżew Avatar answered Sep 29 '22 14:09

Wiktor Stribiżew


You may also try

 sub(' ?$', ' ', x)
 #[1] "blabla1 " "blabla2 "

where

 x <- c("blabla1 ", "blabla2")
like image 25
akrun Avatar answered Sep 29 '22 14:09

akrun