我想根据单词数组检查一个长字符串并选择匹配的单词。这些词可以是多个词 such as
或 This is
或 more。这是我目前所拥有的。
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
正在做它应该做的事情。有没有其他选择?
最佳答案
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} 是插值,就像在字符串中一样。
关于ruby - 如何从出现在数组中的字符串中选择整个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22152024/