19

I'm trying to use the following code to replace two dots for only one:

test<-"test..1"
gsub("\\..", ".", test, fixed=TRUE)

and getting:

[1] "test..1"

I tried several combinations of escape strings, including brackets [] with no success.
What am I doing wrong?

4

1 回答 1

37

如果要使用fixed = TRUE,请使用(未解释的)字符.

> gsub("..", ".", test, fixed = TRUE)

否则,在正则表达式 ( fixed = FALSE) 中,.具有特殊含义(任何字符),因此您需要在其前面加上反斜杠以表示“点字符”:

> gsub("\\.\\.", ".", test)
> gsub("\\.{2}", ".", test)
于 2013-08-30T02:31:36.143 回答