Bala
Bala

Reputation: 11244

How to select whole words from a string that appears in an array?

I want check a long string against array of words and select the matching words. The words could be multi-words such as or This is or more. This is what I have so far.

str = "This is a demo text for demo..."
w = ["This is", "to", "is", "for demo"]     
w.select{ |w| str.include?w } #=>["This is", "is", "for demo"] 

but in this I don't want my result to have "in", "get" etc

str = "This is a demo text for demo together within..."
w = ["This is", "to", "is", "for demo", "in", "get"]    
w.select{ |w| str.include?w } #=> ["This is", "to", "is", "for demo", "in", "get"]

str.include?w is doing what it is supposed to do. Are there any alternatives?

Upvotes: 1

Views: 163

Answers (1)

steenslag
steenslag

Reputation: 80065

str = "This is a demo text for demo..."
w = ["This is", "to", "is", "for demo"]     
p w.select{|w|str =~ /\b#{w}\b/ }

The \b in the regexp is a word boundary; the #{w} is interpolation, just like in strings.

Upvotes: 5

Related Questions