Since the title of the question is "remove the extra whitespace between words", without touching the leading and trailing whitespaces, the answer is (assuming the "words" are non-whitespace character chunks)
gsub("(\\S)\\s{2,}(?=\\S)", "\\1 ", text, perl=TRUE)
stringr::str_replace_all(text, "(\\S)\\s{2,}(?=\\S)", "\\1 ")
## Or, if the whitespace to leep is the last whitespace in those matched
gsub("(\\S)(\\s){2,}(?=\\S)", "\\1\\2", text, perl=TRUE)
stringr::str_replace_all(text, "(\\S)(\\s){2,}(?=\\S)", "\\1\\2")
See regex demo #1 and regex demo #2 and this R demo.
Regex details:
(\S)
- Capturing group 1 (\1
refers to this group value from the replacement pattern): a non-whitespace char
\s{2,}
- two or more whitespace chars (in Regex #2, it is wrapped with parentheses to form a capturing group with ID 2 (\2
))
(?=\S)
- a positive lookahead that requires a non-whitespace char immediately to the right of the current location.