How do I use grepl to specify an exact match of my word from string BUT allow semicolon?

How can I use grepl to return exact matches only, but ignore semicolons? I may be poorly explaining what I want to do, so please see the minimal reprex below of what I'm trying to acheive:

#Define what I want to select
my_choice <- c("and")


my_words1 <- c("sand;sand;land") #Test 1
my_words2 <-c("and;and;and;bland")#Test 2

#Try to get selection with test 1:
> my_words1[grepl(my_choice, my_words1, fixed=TRUE)]
[1] "sand;sand;land"
#^----Not correct! Should return nothing

#Try with test 2:
> my_words2[grepl(my_choice, my_words2, fixed=TRUE)]
[1] "and;and;and;bland"
#^----Also not correct! should return "and;and;and"

That is not how grepl works, it is going to retrieve the entire line where the pattern is found, it doesn't extract subsets o a single character string.

I think you have to separate your string using the semicolons as delimiters, into a character vector, then you can match individual elements.

1 Like

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.