hyco hyco - 2 months ago 13
R Question

R: Trim whitespace within brackets

How can whitespace within brackets be trimmed?

x <- c("the li7(li7, p)b13 reaction")

In this particular case, it should only remove the whitespace between the comma and the p, but I'm looking for a general solution.

cases <-c(
  "(a, b)",
  "( a, b)",
  "a(a, b)",
  "a (a, b)",
  "a (a, b) a(a,b) a(a,b )"

gsub("[[:space:]](?=[^()]*\\))", "", cases, perl = TRUE)
[1] "(a,b)"                 "(a,b)"                 "(a,b)"                
[4] "a(a,b)"                "a (a,b)"               "a (a,b) a(a,b) a(a,b)"

The regex works as follows: when it finds a space, it looks ahead for a right parenthesis. If it finds any other parentheses on the way, it stops and moves on until it finds a space with none. It the replaces that with an empty string.