我有一个regex
无法解决的边缘案例。我需要grep
从字符串中删除前导句点(如果存在)和最后一个句点之后的文本(如果存在)。
也就是说,给定一个向量:
x <- c("abc.txt", "abc.com.plist", ".abc.com")
我想得到输出:
[1] "abc" "abc.com" "abc"
前两种情况已经解决,我在这个相关问题中获得了帮助。但是,对于第三种情况,领先.
我确信这是微不足道的,但我没有建立联系。
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.