From: Xavier Noria Date: 2007-12-16T00:47:07+09:00 Subject: Re: Splitting string into array keeping delimiters On Dec 15, 2007, at 4:39 PM, Sebastian Hungerecker wrote: > Gary C40 wrote: >> If I have this string: >> abcd1234abc123 >> Now I want to separate the digit group with the non-digit group >> into an >> array like this ["abcd",1234,"abc",123]. It's like re.split in >> Python. >> How can I do it in Ruby with the least lines of code possible? >> 'abcd1234abc123'.split(/\d+/) only returns ["abcd","abc"] > > If the regex has capturing groups you'll get those in the array as > well. > 'abcd1234abc123'.split(/(\d+)/) #=> ["abcd", "1234", "abc", "123"] > > If you need the numbers as integers, you could use something like: > 'abcd1234abc123'.scan(/(\D+)(\d+)?/).map {|nd,d| [nd,d.to_i]} > #=> [["abcd", 1234], ["abc", 123]] > (Maybe add flatten and compact) Just another one: 'abcd1234abc123'.scan(/\D+|\d+/) # ["abcd", "1234", "abc", "123"] -- fxn