hyco - 8 months ago 42

R Question

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

```
cases <-c(
"(a,b)",
"(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.

Source (Stackoverflow)