提取特殊字符“/”之间的倒数第二个单词
extracting the second last word between the special characters "/"
我想提取“/”符号后的倒数第二个字符串。例如,
url<- c('https://example.com/names/ani/digitalcod-org','https://example.com/names/bmc/ambulancecod.org' )
df<- data.frame (url)
我想从两者之间的最后一个单词中提取第二个单词 // 并想得到单词 'ani' 和 'bmc'
所以,我尝试了这个
library(stringr)
df$name<- word(df$url,-2)
我需要输出如下:
name
ani
bmc
试试这个:
as.data.frame(sapply(str_extract_all(df$url,"\w{2,}(?=\/)"),"["))[3,]
# V1 V2
#3 ani bmc
as.data.frame(sapply(str_extract_all(df$url,"\w{2,}(?=\/)"),"["))[2:3,]
# V1 V2
#2 names names
#3 ani bmc
使用 basename
的非正则表达式方法
basename(mapply(sub, pattern = basename(url), replacement = "", x = url, fixed = TRUE))
#[1] "ani" "bmc"
basename(url)
"removes all of the path up to and including the last path separator (if any)" 和 returns
[1] "digitalcod-org" "ambulancecod.org"
使用 mapply
将 url
中每个元素的结果替换为 ""
并再次调用 basename
。
可以使用word
,但需要指定分隔符,
library(stringr)
word(url, -2, sep = '/')
#[1] "ani" "bmc"
将gsub
与
结合使用
.*?([^/]+)/[^/]+$
在 R
:
urls <- c('https://example.com/names/ani/digitalcod-org','https://example.com/names/bmc/ambulancecod.org' )
gsub(".*?([^/]+)/[^/]+$", "\1", urls)
这会产生
[1] "ani" "bmc"
这是一个使用strsplit
的解决方案
words <- strsplit(url, '/')
L <- lengths(words)
vapply(seq_along(words), function (k) words[[k]][L[k]-1], character(1))
# [1] "ani" "bmc"
我想提取“/”符号后的倒数第二个字符串。例如,
url<- c('https://example.com/names/ani/digitalcod-org','https://example.com/names/bmc/ambulancecod.org' )
df<- data.frame (url)
我想从两者之间的最后一个单词中提取第二个单词 // 并想得到单词 'ani' 和 'bmc'
所以,我尝试了这个
library(stringr)
df$name<- word(df$url,-2)
我需要输出如下:
name
ani
bmc
试试这个:
as.data.frame(sapply(str_extract_all(df$url,"\w{2,}(?=\/)"),"["))[3,]
# V1 V2
#3 ani bmc
as.data.frame(sapply(str_extract_all(df$url,"\w{2,}(?=\/)"),"["))[2:3,]
# V1 V2
#2 names names
#3 ani bmc
使用 basename
basename(mapply(sub, pattern = basename(url), replacement = "", x = url, fixed = TRUE))
#[1] "ani" "bmc"
basename(url)
"removes all of the path up to and including the last path separator (if any)" 和 returns
[1] "digitalcod-org" "ambulancecod.org"
使用 mapply
将 url
中每个元素的结果替换为 ""
并再次调用 basename
。
可以使用word
,但需要指定分隔符,
library(stringr)
word(url, -2, sep = '/')
#[1] "ani" "bmc"
将gsub
与
.*?([^/]+)/[^/]+$
在
R
:
urls <- c('https://example.com/names/ani/digitalcod-org','https://example.com/names/bmc/ambulancecod.org' )
gsub(".*?([^/]+)/[^/]+$", "\1", urls)
这会产生
[1] "ani" "bmc"
这是一个使用strsplit
words <- strsplit(url, '/')
L <- lengths(words)
vapply(seq_along(words), function (k) words[[k]][L[k]-1], character(1))
# [1] "ani" "bmc"