2

我有一个regex无法解决的边缘案例。我需要grep从字符串中删除前导句点(如果存在)和最后一个句点之后的文本(如果存在)。

也就是说,给定一个向量:

x <- c("abc.txt", "abc.com.plist", ".abc.com")

我想得到输出:

[1] "abc"     "abc.com" "abc"

前两种情况已经解决,我在这个相关问题中获得了帮助。但是,对于第三种情况,领先.

我确信这是微不足道的,但我没有建立联系。

4

1 回答 1

4

This regex does what you want:

^\.+|\.[^.]*$

Replace its matches with the empty string.

In R:

gsub("^\\.+|\\.[^.]*$", "", subject, perl=TRUE);

Explanation:

^      # Anchor the match to the start of the string
\.+    # and match one or more dots
|      # OR
\.     # Match a dot
[^.]*  # plus any characters except dots
$      # anchored to the end of the string.
于 2013-07-25T09:55:51.860 回答