我正在跟进已提出的问题 here关于如何在否定后面的单词中添加前缀“not_”。
在评论中,MrFlick提出了一个使用正则表达式的解决方案gsub("(?<=(?:\\bnot|n't) )(\\w+)\\b", "not_\\1", x, perl=T)
.
我想编辑此正则表达式,以便将 not_ 前缀添加到“not”或“n't”后面的所有单词,直到出现一些标点符号为止。
如果我正在编辑 cptn 的示例,我希望:
x <- "They didn't sell the company, and it went bankrupt"
转变为:
"They didn't not_sell not_the not_company, and it went bankrupt"
使用反向引用在这里还能起到作用吗?如果是这样,任何例子将不胜感激。谢谢!
最佳答案
您可以使用
(?:\bnot|n't|\G(?!\A))\s+\K(\w+)\b
并替换为not_\1
。请参阅regex demo .
详细信息
(?:\bnot|n't|\G(?!\A))
- 三种选择之一:\bnot
- 整个单词not
n't
-n't
\G(?!\A)
- 上一个成功匹配位置的末尾
\s+
- 1 个以上空格\K
- 匹配重置运算符,丢弃目前匹配的文本(\w+)
- 第 1 组(通过替换模式中的\1
引用):1+ 个单词字符(数字、字母或_
)\b
- 单词边界。
R demo :
x <- "They didn't sell the company, and it went bankrupt"
gsub("(?:\\bnot|n't|\\G(?!\\A))\\s+\\K(\\w+)\\b", "not_\\1", x, perl=TRUE)
## => [1] "They didn't not_sell not_the not_company, and it went bankrupt"
关于r - R 中的否定,如何替换 R 中否定后面的单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47774572/