Match sequences of consecutive characters in a string

I have the line "111221" and you want to combine all sets of consecutive equal integers: ["111", "22", "1"] .

I know there is a special regular expression for this, but I don’t remember, and I'm terrible at Googling.

+6
source share
2 answers

Using regex in Ruby 1.8.7 +:

 p s.scan(/((\d)\2*)/).map(&:first) #=> ["111", "22", "1"] 

This works because (\d) captures any digit, and then \2* captures zero or more, which corresponds to that group (second opening bracket). External (…) necessary to capture the entire match as a result in scan . Finally, only scan returned:

 [["111", "1"], ["22", "2"], ["1", "1"]] 

... so we need to run through and save only the first element in each array. In Ruby 1.8.6+ (there is no Symbol#to_proc for convenience):

 p s.scan(/((\d)\2*)/).map{ |x| x.first } #=> ["111", "22", "1"] 

Without Regex, here's an interesting (matching any char) that works in Ruby 1.9.2:

 p s.chars.chunk{|c|c}.map{ |n,a| a.join } #=> ["111", "22", "1"] 

Here's another version that should work even in Ruby 1.8.6:

 p s.scan(/./).inject([]){|a,c| (a.last && a.last[0]==c[0] ? a.last : a)<<c; a } # => ["111", "22", "1"] 
+10
source

you may try

 string str ="111221"; string pattern =@ "(\d)(\1)+"; 

Hope can help you

-2
source

Source: https://habr.com/ru/post/903726/


All Articles