我想检查一个长字符串对齐数组并选择匹配的单词。单词可以是多个单词such as
或This 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
正在做它应该做的事情。还有其他选择吗?
答案 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}是插值,就像在字符串中一样。