我想用ruby在一行文本中搜索给定的单词

时间:2010-09-28 17:09:32

标签: ruby regex

我希望通过正则表达式在一行文本中找到一个给定的单词,但搜索不应只查找整个单词,还要查找单词为prefix或sufix的单词,或者其他单词。例如(我不是很有创意的例子..但它应该得到重点):

在“我住在常绿街道中寻找green,因为绿色的树木绿化。我喜欢绿色乳胶绿色运营商^ 2 $”

应该返回:

evergreen, green, greentown, tree-greenery, green-latex, $green-operator^2$

2 个答案:

答案 0 :(得分:3)

扫描方法有效。该模式会查找运行中字母为绿色的非空格字符。

irb> s = "I live in evergreen street because " +
         "green is greentown with tree-greenery." +
         " I like green-latex $green-operator^2$"

irb> s.scan(/\S*green\S*/)
=> ["evergreen", "green", "greentown", 
    "tree-greenery.", "green-latex", 
    "$green-operator^2$"]

答案 1 :(得分:1)

irb> s = "I live in evergreen street because " +
irb*     "green is greentown with tree-greenery." +
irb*     " I like green-latex $green-operator^2$"

irb> s.split.grep /green/
=> ["evergreen", "green", "greentown", "tree-greenery.", "green-latex", "$green-operator^2$"]