I have a long string with mupltiple instances of pattern. I want the n characters following the pattern. Say that my string is "quick fox jumps over the lazy dog" and I want the two characters after every "u". i.e. I would want a vector c("ic", "mp") as my output. How can I do this?
Thanks!
We can use str_extract_all - create a function (with arguments for the string, n - number of characters, after and the chr - for the character to match
library(stringr)
f1 <- function(string, n, chr)
{
pat <- sprintf("(?<=%s)%s", chr, strrep(".", n))
str_extract_all(string, pat)[[1]]
}
-testing
> f1(str1, 2, "u")
[1] "ic" "mp"
> f1(str1, 3, "u")
[1] "ick" "mps"
str1 <- "quick fox jumps over the lazy dog"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With