在字符串的最后一段时间后删除文本 [英] remove text after final period in string

查看:93
本文介绍了在字符串的最后一段时间后删除文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个难以理解的 grep 谜题:我想在字符串集合的最后一段时间后删除文本(我正在使用R,所以 perl 语法可用)。例如,假设字符串是 ABCD.txt 这个 grep $ b

$ c>会返回 ABCD ,如果文本是 abc.com.foo.bar ,它会返回 abc.com.foo

任何帮助都非常感谢(我不认为我可以喝更多的咖啡!)。

解决方案

以下是一些解决方案:

  sub(^(。*)[。]。*,\\ 1,abc.com.foo.bar)#1 
## [1] abc.com.foo

库(工具)
file_path_sans_ext(abc.com.foo.bar)#3
## [1]abc.com。 foo

ADDED。关于您的评论要求删除主要时段,最简单的方法就是将此输入到以上任何一个 x 是输入字符串的位置:

  sub(^ [。] *,,x)

在一行中执行它们中的任何一个:

  x < -  c(abc。 com.foo.bar,.abc.com.foo.bar,.vimrc)

sub(^ [。] *(。*)[。]?。* $ ,\\1,x)#1a
## [1]abc.com.foo.barabc.com.foo.barvimrc

file_path_sans_ext(sub(^ [。] *,,x))
## [1]abc.com.fooabc.com.foovimrc


I have a grep puzzle that's eluding me: I'd like to remove the text following the final period in a collection of strings (i am using R, so perl syntax is available).

For example, say the string is ABCD.txt this grep would return ABCD, and if the text was abc.com.foo.bar, it would return abc.com.foo.

Any help greatfully appreciated (i don't think i can drink any more coffee!).

解决方案

Here are a few solutions:

sub("^(.*)[.].*", "\\1", "abc.com.foo.bar") # 1
## [1] "abc.com.foo"

library(tools)
file_path_sans_ext("abc.com.foo.bar") # 3
## [1] "abc.com.foo"

ADDED. Regarding your comment asking to remove leading periods, simplest is to just feed this into any of the above where x is the input string:

sub("^[.]*", "", x)

To do any of them in one line:

x <- c("abc.com.foo.bar", ".abc.com.foo.bar", ".vimrc")

sub("^[.]*(.*)[.]?.*$", "\\1", x) # 1a
## [1] "abc.com.foo.bar" "abc.com.foo.bar" "vimrc"          

file_path_sans_ext(sub("^[.]*", "", x))
## [1] "abc.com.foo" "abc.com.foo" "vimrc" 

这篇关于在字符串的最后一段时间后删除文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆