用gsub替换字符串中的两个点

时间:2022-03-28 08:37:47

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?

我尝试了几种转义字符串组合,包括方括号[]没有成功。我究竟做错了什么?

1 个解决方案

#1


31  

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

如果要使用fixed = TRUE,请使用(非解释)字符。

> 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":

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

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

#1


31  

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

如果要使用fixed = TRUE,请使用(非解释)字符。

> 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":

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

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