Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extract n characters after pattern in string in R

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!

like image 681
Tordir Avatar asked Oct 27 '25 04:10

Tordir


1 Answers

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"

data

 str1 <- "quick fox jumps over the lazy dog"
like image 191
akrun Avatar answered Oct 29 '25 20:10

akrun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!