Home > Net >  R exact match for multiple patterns
R exact match for multiple patterns

Time:09-21

I would like to find exact matches for "A1" and "A6" in the vector:

myfile=paste("A",c(1:10),sep="")

I used str_detect from the stringr package:

toMatch <- c("A1", "A6")


str_detect(myfile,fixed(paste(toMatch,collapse="|")))

but it returns TRUE also for partial match with "A10".

Any other funs that could work?

CodePudding user response:

We could use the word boundary (\\b) to avoid the unnecessary partial matches

str_detect(myfile,paste0("\\b(", paste(toMatch, collapse="|"), ")\\b"))
 [1]  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE

Based on the elements used, it can be done with %in%

myfile %in% toMatch
1]  TRUE FALSE FALSE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE
  • Related