【发布时间】:2013-04-09 18:24:36
【问题描述】:
我真的把时间花在学习正则表达式上,而且我正在玩不同的玩具场景。我无法使用的一种设置是从字符串的开头抓取到 n 个字符,其中 n > 1。
这里我可以从字符串的开头抓取到第一个下划线,但我不能将它概括为第二个或第三个下划线。
x <- c("a_b_c_d", "1_2_3_4", "<_?_._:")
gsub("_.*$", "", x)
Here's what I'm trying to achieve with regex. (`sub`/`gsub`):
## > sapply(lapply(strsplit(x, "_"), "[", 1:2), paste, collapse="_")
## [1] "a_b" "1_2" "<_?"
#or
## > sapply(lapply(strsplit(x, "_"), "[", 1:3), paste, collapse="_")
## [1] "a_b_c" "1_2_3" "<_?_."
【问题讨论】: