使用正则表达式在折叠的单词之间插入空格 [英] Use regex to insert space between collapsed words

查看:62
本文介绍了使用正则表达式在折叠的单词之间插入空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究R中的一个弦乐,需要能够将状态名称与match.map()进行匹配.我正在使用的数据集将多个单词的名称放在一起,例如NorthDakota和DistrictOfColumbia.

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"

推荐答案

使用括号捕获匹配的表达式,然后使用\n(R中的\\n)检索它们:

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"

这篇关于使用正则表达式在折叠的单词之间插入空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆