[R] Remove leading and trailing white spaces

jim holtman jholtman at gmail.com
Fri Nov 20 16:59:40 CET 2009


try this:

> x <- '     middle of the string      '
> sub("^[[:space:]]*(.*?)[[:space:]]*$", "\\1", x, perl=TRUE)
[1] "middle of the string"



On Fri, Nov 20, 2009 at 10:51 AM, Bos, Roger <roger.bos at rothschild.com> wrote:
> I have a character string and I would like to remove the leading and
> tailing white spaces.  The example for 'sub' shows how to remove the
> trailing white spaces, but I still can't figure out how to remove both
> trailing and leading white spaces because I can't find any documentation
> for what "+$" means or what "\\s+$" means.  Maybe its because I don't
> have a Unix background.  Thanks in advance for any help with this.
>
> str <- '    Now is the time      '
> sub(' +$', '', str)  ## spaces only
> sub('[[:space:]]+$', '', str) ## white space, POSIX-style
> sub('\\s+$', '', str, perl = TRUE) ## Perl-style white space
>
> Thanks,
>
> Roger
> ***************************************************************
>
> This message is for the named person's use only. It may\...{{dropped:23}}
>
> ______________________________________________
> R-help at r-project.org mailing list
> https://stat.ethz.ch/mailman/listinfo/r-help
> PLEASE do read the posting guide http://www.R-project.org/posting-guide.html
> and provide commented, minimal, self-contained, reproducible code.
>



-- 
Jim Holtman
Cincinnati, OH
+1 513 646 9390

What is the problem that you are trying to solve?




More information about the R-help mailing list