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

I am using Ruby 2.4. I want to find sequential tokens in my array of strings that match a regex. So if my regex is

/\p{L}/

      

and my array

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

      

I want the result to be

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

      

However, my attempt to do this has failed (note that the "neat" 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 sequential tokens in an array that match a pattern that doesn't repeat itself either?

+3


source to share


3 answers


If r

is your regex, usechunk_while



arr.chunk_while { |a,b| a[r] && b[r] }.select { |arr| arr.size > 1 }     
 #=> [["m", "neatty", "fff"]]

      

+3


source


You can also use slice_when

to find the bounds of an auxiliary array that bind the condition:



> arr.slice_when {|x,y| !x[reg] || !y[reg] }.select {|e| e.length>1}
=> [["m", "neatty", "fff"]]

      

+2


source


arr = ["2917", "m", "neatty", "fff", "46", "u", "28", "56", "hi", "%ya!"]
r = /\p{L}/

arr.each_with_object([[]]) { |s,a| s.match?(r) ? (a.last << s) : a << [] }.
    reject { |a| a.size < 2 }
  #=> [["m", "neatty", "fff"], ["hi", "%ya!"]]

      

0


source







All Articles