user3703013
user3703013

Reputation: 13

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

Upvotes: 0

Views: 1880

Answers (1)

Anders Ellern Bilgrau
Anders Ellern Bilgrau

Reputation: 10223

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.

Upvotes: 1

Related Questions