str_extract captures only one instance of recurring keyword

Viewed 882

When I use str_extract() on a string with recurring instances of a certain keyword, it captures only one of them.

> str_extract("1234cAc5678cAc90123", ".....A.....")
[1] "1234cAc5678"

I have two questions:

  1. What is the criterion of choosing one rather than the other? (i.e. "5678cAc9012")
  2. How to make R extract instances each and every time one occurs, regardless of whether the strings overlap or not?

str_extract_all gave 2 instances when the strings are not overlapping, which means str_extract captures just the first instance of the recurring string.

> str_extract_all("1234cAc5678cAc90123", "...A...")
[[1]]
[1] "34cAc56" "78cAc90"

Are there any other function that may show all occurrences even when they overlap, like this:

[1] "1234cAc5678"
[2] "5678cAc9012"

Or even this:

> str_extract("0123A456A7890", "....A....")
[1] "0123A456A"
[2] "A456A7890"
1 Answers

If we are looking for overlapping matches, then use the stri_match_all

library(stringi)
stri_match_all_regex(str1, "(?=(.{5}A.{5}))")[[1]][,2]
#[1] "1234cAc5678" "5678cAc9012"

Or if we are using stringr, which call the stringi, then use str_match_all

str_match_all(str1, "(?=(.{5}A.{5}))")[[1]][,2]
#[1] "1234cAc5678" "5678cAc9012"

str_match_all("0123A456A7890", "(?=(.{4}A.{4}))")[[1]][,2]
#[1] "0123A456A" "A456A7890"

data

str1 <- "1234cAc5678cAc90123"
Related