Reputation: 11244
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
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