hyco hyco - 1 year ago 101
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.

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download