【发布时间】:2018-10-23 12:30:11
【问题描述】:
我无法解决以下问题。请求大家在这方面帮助我。
我的数据中有一系列 &
我的尝试和例子:
string1 <- "This aa should be replaced: but this aaa shouldn't"
string2 <- "This && should be replaced: but this &&& shouldn't"
gsub("aa", "XXX", string1) #1.
gsub("\\baa\\b", "XXX", string1) #2.
gsub("&&", "XXX", string2) #3.
gsub("\\b&&\\b", "XXX", string2) #4.
上面,如果我想匹配string1中的'aa',我可以有两种方法,
在方法 1(表示为:#1)中,我可以简单地传递 'aa' 但这也会部分匹配 'aaa',这是我不想要的,我希望我的正则表达式完全匹配成对的 'a' ,在我的情况下是'aa'。
为了解决这个问题,我使用了正则表达式(#2),在这种情况下它工作正常。
现在,在 string2 中,我预计会有类似的行为,我想要匹配不匹配的一对 '&&' 而不是匹配一对 'a'。
(#3) 尝试有效,但这不是我想要的结果,因为它也部分匹配 '&&&',
(#4) 尝试由于某种原因不起作用,它没有替换字符串。
我的问题是:
1) Why pair of ampersands are not working with boundary conditions ?
2) What is the way around to solve this problem ?
我真的很难过,因此浪费了我一整天,真的感觉很糟糕,尝试在谷歌上找到解决方案,但尚未成功。
如果有人知道,如果它在那里,请将我重定向到一个帖子。或者如果有人发现它是重复的,请告诉我,我会删除它。
感谢您的帮助和阅读问题。
编辑:我的单词边界现在是空格。
输出:
> gsub("aa", "XXX", string1)
[1] "This XXX should be replaced: but this XXXa shouldn't"
> gsub("\\baa\\b", "XXX", string1)
[1] "This XXX should be replaced: but this aaa shouldn't"
>
> gsub("&&", "XXX", string2)
[1] "This XXX should be replaced: but this XXX& shouldn't"
> gsub("\\b&&\\b", "XXX", string2)
[1] "This && should be replaced: but this &&& shouldn't"
>
注意:我也检查了 perl=TRUE,但它不起作用。
【问题讨论】:
-
请定义您的“单词边界”。那是空格和字符串的开始/结束吗?
\b匹配字符串的开始/结束与单词 char 之间的位置,或单词与非单词 char 之间的位置。 -
然后使用
gsub("(?<!\\S)&&(?!\\S)", "XXX", string2, perl=TRUE)。您误解了\b的作用以及正则表达式中的“单词”是什么。