[R] gsub regex simplification

Thaler,Thorn,LAUSANNE,Applied Mathematics Thorn.Thaler at rdls.nestle.com
Wed May 8 11:08:02 CEST 2013


Dear all,

I want to use gsub to change a vector of strings. Basically, I want to replace any dot by a space, remove the possibly appended ".f" and I want to capitalize each word. I did that by chaining multiple gsubs together, but I was wondering (for the sake of learning - maybe the current version is more readable) whether I could do that with a _single_ gsub call?

Thanks for your help!

txt <- c("example1", "example2.f", "another.example3.f", "yet.another.example4.f")
gsub("(^|[[:space:]])([[:alpha:]])", "\\1\\U\\2",
       gsub("\\.", " ", gsub("\\.f", "", txt)),
       perl = TRUE)

Thanks for your input!

Kind Regards,

Thorn Thaler 
NRC Lausanne
Applied Mathematics
+41 21 785 8220



More information about the R-help mailing list