This question already has answers here:
How to replace many special characters with “something plus special characters” in R

(3个答案)


5年前关闭。




我有一串字符。
str = c(".wow", "if.", "not.confident", "wonder", "have.difficulty", "shower")

我正在尝试替换“。”在带有空格的单词之间。所以看起来像这样
".wow", "if.", "not confident", "wonder", "have difficulty", "shower"

首先,我尝试
gsub("[\\w.\\w]", " ", str)
[1] "  o "            "if"              "not confident"   " onder"
[5] "have difficulty" "sho er "

它给了我想要的空白,但是却砍掉了所有的w。然后,我尝试
gsub("\\w\\.\\w", " ", str)
[1] ".wow"          "if"            "no onfident"   "wonder"
[5] "hav ifficulty" "shower."

它保留了w,但是在“。”之前和之后带走了其他字符。

我也不能用
gsub("\\.", " ", str)
[1] " wow"             "if "              "not.confident"   "wonder"
[5] "have.difficulty" "shower"

因为它将带走“。”不在单词之间。

最佳答案

尝试

gsub('(\\w)\\.(\\w)', '\\1 \\2', str)
#[1] ".wow"            "if."             "not confident"   "wonder"
#[5] "have difficulty" "shower"

要么
gsub('(?<=[^.])[.](?=[^.])', ' ', str, perl=TRUE)

或@rawr建议
gsub('\\b\\.\\b', ' ', str, perl = TRUE)

关于regex - 如何在R中的单词之间替换特殊字符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29476002/

10-13 01:14