Regex in r to add space after period (if not present)

Viewed 519

I imported text files into r and I am using a function that determines the end of sentence by period followed by space . some of the sentences do not have space after the period, so I am trying to write the regex that fixes that. The regex has to be specific to periods that are followed by words (not digits), so it won't insert space after decimal points.

I try this regex on the example below, this works but it replaces the first letter after the period with space. I am trying to add the space between the period and the next word without deleting.

thank you

x = " In water, the hydrogen atoms are close to two corners of a tetrahedron centered on the oxygen.At the other two corners are lone pairs of valence electrons that do not participate in the bonding.In a perfect tetrahedron, the atoms would form a 109.5° angle."

gsub("\\.([A-Za-z])", ". ", x)
1 Answers

You can use positive lookahead so that so that you don't miss the first letter after the period.

gsub("\\.(?=[A-Za-z])", ". ", x, perl = TRUE)

#" In water, the hydrogen atoms are close to two corners of a tetrahedron 
#centered on the oxygen. At the other two corners are lone pairs of valence 
#electrons that do not participate in the bonding. In a perfect 
#tetrahedron, the atoms would form a 109.5° angle."
Related