stringr
uses ICU
基于正则表达式。因此,一个选项是使用正则表达式环视,但这里的长度不固定,因此(?<=
行不通的。另一种选择是删除子字符串str_remove
or use str_replace
匹配并捕获第三个没有的单词_
([^_]+
)并替换为反向引用(\\1
) 捕获的单词
library(stringr)
str_replace(my_string, "^[^_]+_[^_]+_([^_]+)_.*", "\\1")
[1] "textimput"
如果我们只需要子字符串
str_replace(my_string, "^[^_]+_[^_]+_([^_]{4}).*", "\\1")
[1] "text"
In base R
,更容易strsplit
并通过索引获取第三个单词
strsplit(my_string, "_")[[1]][3]
# [1] "textimput"
Or use perl = TRUE
in regexpr
regmatches(my_string, regexpr("^([^_]+_){2}\\K[^_]+", my_string, perl = TRUE))
# [1] "textimput"
对于子串
regmatches(my_string, regexpr("^([^_]+_){2}\\K[^_]{4}", my_string, perl = TRUE))
[1] "text"