How do I find consecutive strings in my array that match a regex?

Viewed 260

I'm using Ruby 2.4. I want to find consecutive tokens in my array of strings that match a regular expression. So if my regex is

/\p{L}/

and my array is

 ["2917", "m", "neatty", "fff", "46", "u", "28", "56"]

I would want the result to be

["m", "neatty", "fff"]

However, my attempt to do this has failed (notice the "neatty" token is repeated) ...

2.4.0 :020 > arr = ["2917", "m", "neatty", "fff", "46", "u", "28", "56"]
 => ["2917", "m", "neatty", "fff", "46", "u", "28", "56"]
2.4.0 :021 > arr.each_cons(2).select{|pair| pair.all?{|elem| elem =~ /\p{L}/ }}.flatten
 => ["m", "neatty", "neatty", "fff"]

How do I find consecutive tokens in an array that match a pattern that also don't repeat?

3 Answers
Related