在字符串中除第一个点外,删除所有的点

5

我想要替换除第一个连续点号以外的所有点号。以下是我想要的示例:

> 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?

如何使用正则表达式解决这个问题?

很简单,你可以用"."代替".+"。 - Civa
1个回答

6

在您的第一个正则表达式中,将""替换为"."

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

这也是有效的。基本上,您将所有点和连续点替换为单个点。

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

Joshua谢谢。我知道这很明显,只是我没看到... :) - Samo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接