使用 gsub 替换 R 中的多个单词
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)
参见 the regex demo。
详情
\b
- 单词边界
SE Kellogg
- 文字子串
\b
- 单词边界
(?!\s+Court\b)
- 如果在当前位置的右侧紧邻有
\s+
- 一个或多个空白字符
Court\b
- 一个完整的单词 Court
.
> gsub("\bSE Kellogg\b(?!\s+Court\b)", "SE Kellogg Court", address, perl=TRUE)
[1] "SE Kellogg Court" "SE Kellogg Court"
请注意,如果您在搜索短语周围使用捕获组 ((...)
) 并在替换模式中使用 </code> 反向引用,则可能会缩短替换:</p>
<pre><code>gsub("\b(SE Kellogg)\b(?!\s+Court\b)", "\1 Court", address, perl=TRUE)
^ ^ ^^^
我无法尝试规范化一堆地址。使用 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)
参见 the regex demo。
详情
\b
- 单词边界SE Kellogg
- 文字子串\b
- 单词边界(?!\s+Court\b)
- 如果在当前位置的右侧紧邻有\s+
- 一个或多个空白字符Court\b
- 一个完整的单词Court
.
> gsub("\bSE Kellogg\b(?!\s+Court\b)", "SE Kellogg Court", address, perl=TRUE)
[1] "SE Kellogg Court" "SE Kellogg Court"
请注意,如果您在搜索短语周围使用捕获组 ((...)
) 并在替换模式中使用 </code> 反向引用,则可能会缩短替换:</p>
<pre><code>gsub("\b(SE Kellogg)\b(?!\s+Court\b)", "\1 Court", address, perl=TRUE)
^ ^ ^^^