Reputation: 508
I have a vector of text strings containing smilies and a dictionary containing only the smilies.
A <- c("This :/ :/ :) ^^","is :/ ^^", "weird^^ :)")
B <- c(":)",":/","^^")
I would like to extract all matches of smilies for each text string including duplicates, so my output should look like this:
[[1]]
[1] ":/" ":/" ":)" "^^"
[[2]]
[1] ":/" "^^"
[[3]]
[1] "^^" ":)"
This is what I tried so far:
# does not return duplicates
sapply(A, function(x) B[str_detect(x, fixed(B))], USE.NAMES = FALSE)
[[1]]
[1] ":)" ":/" "^^"
[[2]]
[1] ":/" "^^"
[[3]]
[1] ":)" "^^"
# Only returns first instance
str_extract_all(A,fixed(B))
[[1]]
[1] ":)"
[[2]]
[1] ":/"
[[3]]
[1] "^^"
# returns error because of unescaped characters
rm_default(A,pattern=B,fixed=TRUE,extract=TRUE)
Error in stringi::stri_extract_all_regex(text.var, pattern) :
Incorrectly nested parentheses in regexp pattern. (U_REGEX_MISMATCHED_PAREN)
In addition: Warning messages:
1: In if (substring(pattern, 1, 4) == "@rm_") { :
the condition has length > 1 and only the first element will be used
2: In if (substring(pattern, 1, 1) == "@") { :
the condition has length > 1 and only the first element will be used
Any help is much appreciated.
Upvotes: 2
Views: 279
Reputation: 626804
You may build a regex dynamically using the items in your B
list by first sorting the items by length in a descending order (so that if you have :))
and :)
the first could be extracted - that is a requirement for an unanchored NFA expression where the first alternative in an alternation group "wins", see [the Remember That The Regex Engine Is Eager section), and escape each item. Then just call regmatches
/ stringr::str_extract_all
:
regex.escape <- function(string) {
gsub("([][{}()+*^${|\\\\?.])", "\\\\\\1", string)
}
sort.by.length.desc <- function (v) v[order( -nchar(v)) ]
A <- c("This :/ :/ :) ^^","is :/ ^^", "weird^^ :)")
B <- c(":)",":/","^^")
B <- sort.by.length.desc(B)
pattern <- paste(regex.escape(B), collapse="|")
regmatches(A, gregexpr(pattern, A))
See the R demo online.
In this case, the pattern will be :\)|:/|\^\^
and the output will be
[[1]]
[1] ":/" ":/" ":)" "^^"
[[2]]
[1] ":/" "^^"
[[3]]
[1] "^^" ":)"
Upvotes: 2
Reputation: 887118
One option is to do strsplit
and then extract the elements that are contained in 'B'
lapply(strsplit(A, "[A-Za-z ]"), function(x) x[x %in% B])
#[[1]]
#[1] ":/" ":/" ":)" "^^"
#[[2]]
#[1] ":/" "^^"
#[[3]]
#[1] "^^" ":)"
Upvotes: 1