如何从数组中出现的字符串中选择整个单词?

时间:2014-03-03 16:29:56

标签: ruby

我想检查一个长字符串对齐数组并选择匹配的单词。单词可以是多个单词such asThis is或更多。这是我到目前为止所做的。

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"] 

但在此我不希望我的结果有“in”,“get”等

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正在做它应该做的事情。还有其他选择吗?

1 个答案:

答案 0 :(得分:5)

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

正则表达式中的\ b是一个单词边界; #{w}是插值,就像在字符串中一样。