【发布时间】:2018-08-06 07:41:03
【问题描述】:
我在一个字符向量中有许多 URL,我正在尝试使用 base R 从它们中提取子字符串。我想提取两种类型的子字符串:
- 字符串中最后一个斜杠 (/) 之后和最后一个下划线 (_) 之前的子字符串。
- 最后一个下划线 (_) 之后和子字符串 .tar.gz 之前的子字符串。
我已经找到了一个解决方案,但它涉及许多不必要的步骤。有没有办法使用每个子字符串的单个正则表达式来完成此操作?
以下是我的工作示例:
# An example URL
a <- "https://cran.r-project.org/src/contrib/Archive/ggplot2/ggplot2_0.4.5.tar.gz"
# Keep everything after the last slash
b <- sub('.*\\/', '', a)
# Keep everything before .tar.gaz
c <- sub('.tar.*', '', b)
# Extract desired strings based on underscore
foo <- sub('.*\\_', '', c)
bar <- sub('\\_.*', '', c)
对于这个例子来说,使用基数 R 很重要。
【问题讨论】:
-
对于给定的例子,这可以工作:
sub(".tar.*", "", strsplit(basename(a), "_")[[1]]),但它可能不适用于更复杂的文件。 -
这太棒了!我不知道 basename()。将其添加为答案。