I want to search for a given word in a line of text with ruby
I want to find a given word in a line of text through a regular expres开发者_StackOverflow中文版sion, but the search should not just look for the whole word, but also instances where the word is prefix or sufix, or inside other words. For example (I'm not very creative with examples.. but it should get the point):
Look for green
in "I live in evergreen street because green is greentown with tree-greenery. I like green-latex $green-operator^2$"
should return:
evergreen, green, greentown, tree-greenery, green-latex, $green-operator^2$
The scan method works. The pattern looks for a run of non-space characters that have the letters green in the run.
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$"]
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$"]
精彩评论