我有一个包含多个模式实例的长字符串。我想要模式后的 n 个字符。假设我的字符串是
"quick fox jumps over the lazy dog"
,我想要每个 "u"
之后的两个字符。即我想要一个矢量c("ic", "mp")
作为我的输出。我该怎么做?
谢谢!
我们可以使用
str_extract_all
- 创建一个函数(带有字符串参数,n
- 字符数,之后和 chr
- 用于匹配的字符
library(stringr)
f1 <- function(string, n, chr)
{
pat <- sprintf("(?<=%s)%s", chr, strrep(".", n))
str_extract_all(string, pat)[[1]]
}
-测试
> f1(str1, 2, "u")
[1] "ic" "mp"
> f1(str1, 3, "u")
[1] "ick" "mps"
str1 <- "quick fox jumps over the lazy dog"
类似但使用
str_extract_all
和paste0
:
要点:
(?<=)
是一个 lookbehind,与模式匹配但 does not include it in the extracted string.
.{n}
匹配模式后的下一个n
字符。
library(stringr)
n <- 2
str_extract_all(string, paste0("(?<=", "u", ").{", n, "}"))[[1]]
[1] "ic" "mp"