R Regex / gsub : How to collapse spaces in a string

gsub, perl, r, regex

Solution

Maybe

> x<-"The d og is br own."
> gsub(" (.) "," \\1",x)
[1] "The dog is br own."

or

gsub(" ([[:alnum:]]) "," \\1",x)

`(.)` matches anything `([[:alnum:]])` matches alphanumeric characters only.

Problem

I have a vector of sentences that were scanned from handwritten documents. In the process there were some spacing problems like this: ``` The d og is br own. ``` I was curious if there was a way to generically take any pattern with `'_x_'` or space-character-space and collapse the second space like this: ``` The d og is br own. --> The dog is br own. ``` I'm only worried about a single character between the spaces (`'_x_'` NOT `'_xx_'`). Any suggestions?

Original source