Daniel W. wrote:
Hi all, I’ve an interesting problem. Imagine the following string:
‘a1000aa’
I want to break it apart like so:
[ ‘a’, ‘1000’, ‘aa’ ]
I did a search on the forums and came up with this regex:
‘a1000aa’.scan(/((.)\2*)/).map { |i| i[0] }
Which is pretty close, but it groups on a change of character, so I
would get:
[ ‘a’, ‘1’, ‘000’, ‘aa’ ]
I tried playing around with the regex (e.g. swapping the . for (\d|\w))
but to no avail.
Any ideas?
I figured out one possible solution. Granted, it’s not as elegant as a
single regex, but it works and I understand it. Here goes…
First, I opened up class String to add some convenience and make things
a bit shorter:
class String
def letter?
self.first.scan(/[A-Za-z]/).empty? ? false : true
end
def digit?
self.first.scan(/[0123456789]/).empty? ? false : true
end
end
Any my method:
def break_apart_rule_increment
groups = Array.new
string = ‘a1000aa’
string.each_char do |character|
# Put the first character into a group.
groups << character and next if groups.empty?
# If this character is of the same kind as the last,
# add it to the group, otherwise, create a new group
# and put it there.
if (groups.last.letter? and character.letter?) or
(groups.last.digit? and character.digit?)
groups.last << character
else
groups << character
end
end
groups
end