删除除了charchter字符串中的第一个点之外的所有点

时间:2021-08-06 16:52:33

After spending hours searching for an answer and since it is 3:15 AM in final stages of desperation I am asking this basic question (since I know nothing about regular expressions).

在花了好几个小时寻找答案之后,因为在绝望的最后阶段凌晨3:15,我问这个基本问题(因为我对正则表达式一无所知)。

I want to replace all but first consecutive dots. Here is an example of what I want:

我想替换除了第一个连续点以外的所有点。这是我想要的一个例子:

> names.orig <- c("test & best", "test & worse &&&&  ? do")
> names <- make.names(names.orig)
> names
[1] "test...best"             "test...worse.........do"
> 
> # But I want this instead:
> # [1] "test.best"             "test.worse.do"
> 
> # Desperatley tried:
> gsub("\\.{2, }", "", names)
[1] "testbest"    "testworsedo"
> gsub("\\G((?!^).*?|[^\\.]*\\.*?)\\.", "", names)
Error in gsub("\\G((?!^).*?|[^\\.]*\\.*?)\\.", "", names) : 
  invalid regular expression '\G((?!^).*?|[^\.]*\.*?)\.', reason 'Invalid regexp'
> # etc.
> 
> # The only thing that works for me is this
> unlist(lapply(strsplit(names, "\\."), function(x) paste(x[x != ""], collapse=".")))
[1] "test.best"     "test.worse.do"
> 
> # But, really, what is the right regex in combination with what?

Any hints on how to solve this with regex appreciated.

关于如何用正则表达式解决这个问题的任何提示都表示赞赏。

1 个解决方案

#1


6  

Replace the "" with "." in your first regex:

将“”替换为“。”在你的第一个正则表达式:

R> nms <- make.names(c("test & best", "test & worse &&&&  ? do"))
R> gsub("\\.{2, }", ".", nms)
[1] "test.best"     "test.worse.do"

This also works. Basically, you're replacing all dots and consecutive dots with a single dot.

这也有效。基本上,您用一个点替换所有点和连续点。

R> gsub("\\.+", ".", nms)
[1] "test.best"     "test.worse.do"

#1


6  

Replace the "" with "." in your first regex:

将“”替换为“。”在你的第一个正则表达式:

R> nms <- make.names(c("test & best", "test & worse &&&&  ? do"))
R> gsub("\\.{2, }", ".", nms)
[1] "test.best"     "test.worse.do"

This also works. Basically, you're replacing all dots and consecutive dots with a single dot.

这也有效。基本上,您用一个点替换所有点和连续点。

R> gsub("\\.+", ".", nms)
[1] "test.best"     "test.worse.do"