Regex - filter with (1) hyphen or (2) end of sentence

Viewed 81

I need support with RegEx filtering!

I have a list of keywords and many rows that should be checked. In this example, the keyword "-book-" can be (1) in the middle of the sentence or (2) at the end, which would mean that the last hyphen is not present.

I need a RegEx expression, which identifies "-book-" and "-book". I don't want similar keywords like "-booking-" etc to be identified.

library(dplyr)
keywords = c( "-album-",  "-book-", "-castle-")                 
search_terms = paste(keywords, collapse ="|")                
number = c(1:5)
sentences = c("the-best-album-in-shop", "this-book-is-fantastic", "that-is-the-best-book", "spacespacespace", "unwanted-sentence-with-booking")   
data = data.frame(number, sentences)  
output = data %>% filter(., grepl( search_terms, sentences) )               
# Current output:
 number              sentences
1      1 the-best-album-in-shop
2      2 this-book-is-fantastic
# DESIRED output:
  number              sentences
1      1 the-best-album-in-shop
2      2 this-book-is-fantastic
3      3  that-is-the-best-book
3 Answers

The -book- pattern will match a whole word book with hyphen on the left and right.

To match a whole word book with a hyphen on the left or right, you need an alternation \bbook-|-book\b.

Thus, you can use

keywords = c( "-album-",  "\\bbook-", "-book\\b", "-castle-" ) 

You could also do:

subset(data, grepl(paste0(sprintf("%s?\\b",keywords),collapse = "|"), sentences))

  number              sentences
1      1 the-best-album-in-shop
2      2 this-book-is-fantastic
3      3  that-is-the-best-book

Note that this will only check for the -book- at the (1) in the middle of the sentence or (2) at the end Not at the beginning

Another solution you can take it into account

library(stringr)
data %>% 
  filter(str_detect(sentences, regex("-castle-|-album-|-book$|-book-\\w{1,}")))
#   number              sentences
# 1      1 the-best-album-in-shop
# 2      2 this-book-is-fantastic
# 3      3  that-is-the-best-book
Related