我正在研究R中的等值线,并且需要能够使用match.map()匹配状态名称.我正在使用的数据集将多个单词的名称粘在一起,如NorthDakota和DistrictOfColumbia.
如何使用正则表达式在低位字母序列之间插入空格?我已成功添加了一个空格,但无法保留指示空间位置的字母.
places = c("NorthDakota", "DistrictOfColumbia")
gsub("[[:lower:]][[:upper:]]", " ", places)
[1] "Nort akota" "Distric olumbia"
Run Code Online (Sandbox Code Playgroud)
Ben*_*ker 11
使用括号捕获匹配的表达式,然后\n
(\\n
在R中)检索它们:
places = c("NorthDakota", "DistrictOfColumbia")
gsub("([[:lower:]])([[:upper:]])", "\\1 \\2", places)
## [1] "North Dakota" "District Of Columbia"
Run Code Online (Sandbox Code Playgroud)
hwn*_*wnd 11
您希望使用捕获组捕获到匹配的上下文,以便您可以返回替换呼叫中的每个匹配组.要访问组,请在两个反斜杠\\
后跟组#
.
> places = c('NorthDakota', 'DistrictOfColumbia')
> gsub('([[:lower:]])([[:upper:]])', '\\1 \\2', places)
# [1] "North Dakota" "District Of Columbia"
Run Code Online (Sandbox Code Playgroud)
另一种方法,PCRE
通过使用perl=T
和使用外观断言来打开.
> places = c('NorthDakota', 'DistrictOfColumbia')
> gsub('[a-z]\\K(?=[A-Z])', ' ', places, perl=T)
# [1] "North Dakota" "District Of Columbia"
Run Code Online (Sandbox Code Playgroud)
说明:
该\K
转义序列重置报道比赛的出发点和任何先前消耗字符不再包括在内.基本上(抛弃与此相匹配的所有内容.)
[a-z] # any character of: 'a' to 'z'
\K # '\K' (resets the starting point of the reported match)
(?= # look ahead to see if there is:
[A-Z] # any character of: 'A' to 'Z'
) # end of look-ahead
Run Code Online (Sandbox Code Playgroud)