如何从R中的URL路径提取文本



我有一个数据帧,其中有一列的条目格式为:

/textIwant
/textIwant/otherstuff
/

我想创建一个新的列提取"textIwant"。我应该使用strsplit还是regex?

我们可以使用str_extract提取一个或多个不是/的字符

library(stringr)
str_extract(str1,  "[^/]+")
#[1] "textIwant"   "textIwant"   "abc-def-ghi" "abc-def-ghi"

或者使用base R中的sub来匹配不是/的字符,将其捕获为一个组(([^/]+)(并替换为反向引用(\1(

sub("^.([^/]+).*", "\1", str1)
#[1] "textIwant"   "textIwant"   "abc-def-ghi" "abc-def-ghi"

数据

str1 <- c("/textIwant", "/textIwant/otherstuff", "/abc-def-ghi/", "/abc-def-ghi")

我会使用

basename(str1)
[1] "textIwant"   "otherstuff"  "abc-def-ghi" "abc-def-ghi"

str1来自akrun的例子:

str1 <- c("/textIwant", "/textIwant/otherstuff", "/abc-def-ghi/", "/abc-def-ghi")

实际上,可以使用在/上进行拆分的strsplit()

sapply(strsplit(str1, "/"), "[", 2)
# "textIwant"   "textIwant"   "abc-def-ghi" "abc-def-ghi"

最新更新