简体   繁体   中英

Multiple pattern Matching in R

For a multiple pattern matches (present in a character vector), i tried to apply grep(paste(States,collapse="|), Description) . It works fine, but the problem here is that

Consider,

Descritpion=C("helloWorld Washington DC","Hello Stackoverflow////Newyork RBC")
States=C("DC","RBC","WA")

if the multiple pattern match for "WA" in the Description Vector. My function works for "helloWorld **Wa**shington DC" because "WA" is present. But i need a suggestion regarding the search pattern not in the whole String but at the end of String here with DC,RBC.

Thanks in advance

I guess you want something like the following. I've taken the liberty to clean up your example a bit.

Description <- c("helloWorld Washington DC", "Hello Stackoverflow", "Newyork RBC")
States <- c("DC","RBC","WA")

search.string <- paste0(States, "$", collapse = "|") # Construct the reg. exprs.
grep(search.string, Description, value = TRUE) 
#[1] "helloWorld Washington DC" "Newyork RBC"   

Note, we use $ to signify end-of-string match.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM