Preferably using the stringr
package, I want to create a function extract()
that takes for argument a vector of strings
vec <- c(
"div(span(icon(\"hospital-user\"), i18n$t(\"Enrolments\"), \"or\", i18n$t(\"Paper\"))),",
"a string with no matching pattern",
"Lala i18n$t(\"Rock\")"
)
and return all elements inside i18n$t(\""\)
.
In the above example, extract(vec)
would return "Enrolments"
, "Paper"
, "Rock"
.
CodePudding user response:
We can use a regex lookaround to extract the word (\\w
) that follows a the n$t("
. The $
is metacharacter, so just escape (\\
) it
library(stringr)
str_extract_all(vec, '(?<=n\\$t\\(")\\w ')[[1]]
[1] "Enrolments" "Paper" "Rock"
If there are more than one element, use unlist
unlist(str_extract_all(vec, '(?<=n\\$t\\(")\\w '))