Use regex to insert space between collapsed words

gsub, r, regex

Solution

Use parentheses to capture the matched expressions, then `\n` (`\\n` in R) to retrieve them:

places = c("NorthDakota", "DistrictOfColumbia")
gsub("([[:lower:]])([[:upper:]])", "\\1 \\2", places)
## [1] "North Dakota"         "District Of Columbia"

Problem

I'm working on a choropleth in R and need to be able to match state names with match.map(). The dataset I'm using sticks multi-word names together, like NorthDakota and DistrictOfColumbia. How can I use regular expressions to insert a space between lower-upper letter sequences? I've successfully added a space but haven't been able to preserve the letters that indicate where the space goes. ``` places = c("NorthDakota", "DistrictOfColumbia") gsub("[[:lower:]][[:upper:]]", " ", places) [1] "Nort akota" "Distric olumbia" ```

Original source

Related problems