[英]Using gsub to replace multiple words in R
我一直在试图规范化一堆地址。 使用gsub()
时,是否存在与\\\\b\\\\b
类似的正则表达式,但是可以替换多个单词?
address <- c("SE Kellogg", "SE Kellogg Court")
gsub("\\bSE Kellogg\\b", "SE Kellogg Court", address)
#desired output:
"SE Kellogg Court" "SE Kellogg Court"
# actual output
"SE Kellogg Court" "SE Kellogg Court Court"
您可以使用前瞻性为负的PCRE正则表达式:
\bSE Kellogg\b(?!\s+Court\b)
参见regex演示 。
细节
\\\\b
单词边界 SE Kellogg
文字子字符串 \\\\b
单词边界 (?!\\\\s+Court\\\\b)
-如果当前位置右侧立即有匹配项,则匹配失败的负前行
\\\\s+
-一个或多个空格字符 Court\\\\b
整个单词Court
。 R演示 :
> gsub("\\bSE Kellogg\\b(?!\\s+Court\\b)", "SE Kellogg Court", address, perl=TRUE)
[1] "SE Kellogg Court" "SE Kellogg Court"
请注意,如果在搜索短语周围使用捕获组( (...)
),并在替换模式中使用\\1
反向引用,则可以缩短替换时间:
gsub("\\b(SE Kellogg)\\b(?!\\s+Court\\b)", "\\1 Court", address, perl=TRUE)
^ ^ ^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.