转义R中的所有标点字符

时间:2017-05-23 09:23:23

标签: r regex escaping

考虑使用字符串:string<- "The qu!ck, brown fox jumps over the lazy d*g!"并且您希望避开所有标点符号。因此:

escaped_string<-"The qu\\!ck\\, brown fox jumps over the \\`lazy\\` d\\*g" 

我没有成功尝试过:

>gsub(pattern = "[[:punct:]]",replacement="\\1",string)
[1] "The quck brown fox jumps over the lazy dg

思考?想法?

1 个答案:

答案 0 :(得分:4)

您需要使用捕获组并使用

string <- "The qu!ck, brown fox jumps over the `lazy` d*g!"
gsub(pattern = "([[:punct:]])",replacement="\\\\\\1",string)
[1] "The qu\\!ck\\, brown fox jumps over the \\`lazy\\` d\\*g\\!"

请参阅online R demo

([[:punct:]])中的一对非转义括号创建了一个捕获组,您可以使用替换模式中的\1反向引用来访问该组。替换模式应定义为"\\\\\\1",因为要替换为文字反斜杠,您需要转义文字反斜杠(因此,"\\\\"表示替换反斜杠),反向引用应定义为{{1 (还需要一个文字反斜杠)。