【发布时间】:2016-09-26 08:27:23
【问题描述】:
我正在尝试删除第一个连字符之后出现的所有数字/字符。 这里有一些例子:
15-103025-01
800-40170-02
68-4974-01
我想要的输出:
15-
800-
68-
我读过这样的帖子:
- Using gsub to extract character string before white space in R
- truncate string from a certain character in R
- Truncating the end of a string in R after a character that can be present zero or more times
但它们不是我想要的,因为其中提到的方法也会去掉我的连字符(只留下前 2 或 3 个数字)。
这是我迄今为止尝试过的:
gsub(pattern = '[0-9]*-$', replacement = "", x = data$id)
grep(pattern = '[0-9]*-', replacement = "", x = data$id)
regexpr(pattern = '[0-9]*-', text = data$id)
但并没有像我预期的那样真正工作。
【问题讨论】:
-
sub("(?<=-).*", "", x, perl = TRUE)怎么样,使用sub()表示-的第一次出现,(?<=-)用于积极的向后看以保留-,并使用.*删除其后的所有内容. -
嗨@RichardScriven 你能解释一下每个组件的含义吗?比如 "(?
-
刷新以查看我更新的评论
-
@RichardScriven 它有效!太感谢了!所以你说 sub() 只能用于第一个连字符?如果我现在想使用第二个连字符作为指南呢???
-
那就更难了:)