FAC
FAC

Reputation: 193

Replace two dots in a string with gsub

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?

Upvotes: 19

Views: 20519

Answers (1)

flodel
flodel

Reputation: 89057

If you are going to use fixed = TRUE, use the (non-interpreted) character .:

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

Otherwise, within regular expressions (fixed = FALSE), . has a special meaning (any character) so you'll want to prefix it with a backslash to mean "the dot character":

> gsub("\\.\\.", ".", test)
> gsub("\\.{2}", ".", test)

Upvotes: 37

Related Questions