regex - 如何在R中的单词之间替换特殊字符

标签 regex r substitution

<分区>

我有一串字符。

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" 

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

最佳答案

使用 capturing groups and back-references :

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

可以通过将要分组的字符放在一组括号 ( ... ) 中来创建捕获组。反向引用记忆捕获组匹配的内容。

反向引用指定为 (\);后跟一个数字表示组的编号

使用 lookaround断言:

Lookarounds are zero-width assertions. They don't "consume" any characters on the string.

sub('(?<=\\w)\\.(?=\\w)', ' ', str, perl = TRUE)

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

相关文章:

python - 带有可选捕获组和否定前瞻的正则表达式

regex - 使用 dplyr 在选定的列上添加具有行均值的列

r - R语言中的着色输出

regex - 如果以逗号结尾,如何从 Google Sheets 单元格的末尾删除逗号?

algorithm - 求解递归的代入法

arrays - 在 Matlab 中结合 cellfun 和 subs

python - 高效的嵌套正则表达式

python - "raw string regex"究竟是什么,你如何使用它?

javascript - 正则表达式匹配 &foo= 之间的所有内容,直到它再次出现

R 中 difftime 的结果与 excel 和 timeanddate.com 不同