What's the best way to split this kind of string?

S

Sam Kong

Hi!

I'm trying to make a routine to make a Morris Number Sequence.
(http://www.ocf.berkeley.edu/~stoll/number_sequence.html)
I need to split a string in the following way, for example.

"111223133" => ["111", "22", "3", "1", "33"]

I can loop thru the string by each character, comparing with the
previous character.
But is there a quick and easy way?
Probably a regular expression?

Thanks.

Sam
 
J

Jim Weirich

Sam said:
Hi!

I'm trying to make a routine to make a Morris Number Sequence.
(http://www.ocf.berkeley.edu/~stoll/number_sequence.html)
I need to split a string in the following way, for example.

"111223133" => ["111", "22", "3", "1", "33"]

I can loop thru the string by each character, comparing with the
previous character.
But is there a quick and easy way?
Probably a regular expression?

This seems to work:

"111223133".scan(/1+|2+|3+|4+|5+|6+|7+|8+|9+|0+/)
=> ["111", "22", "3", "1", "33"]
 
R

Ross Bamford

Hi!

I'm trying to make a routine to make a Morris Number Sequence.
(http://www.ocf.berkeley.edu/~stoll/number_sequence.html)
I need to split a string in the following way, for example.

"111223133" => ["111", "22", "3", "1", "33"]

I can loop thru the string by each character, comparing with the
previous character.
But is there a quick and easy way?
Probably a regular expression?

Maybe something like:

s.scan(/(\d)(\1*)/).map! { |e| e.join }
# => ["111", "22", "3", "1", "33"]

or:

s.scan(/0+|1+|2+|3+|4+|5+|6+|7+|8+|9+/)
# => ["111", "22", "3", "1", "33"]
 
W

William James

Sam said:
Hi!

I'm trying to make a routine to make a Morris Number Sequence.
(http://www.ocf.berkeley.edu/~stoll/number_sequence.html)
I need to split a string in the following way, for example.

"111223133" => ["111", "22", "3", "1", "33"]

I can loop thru the string by each character, comparing with the
previous character.
But is there a quick and easy way?
Probably a regular expression?

Thanks.

Sam

"111223133".scan(/(.)(\1*)/).map{|x|x.join}
 
A

Andrew Johnson

[snip]
Maybe something like:

s.scan(/(\d)(\1*)/).map! { |e| e.join }
# => ["111", "22", "3", "1", "33"]

or:

s.scan(/0+|1+|2+|3+|4+|5+|6+|7+|8+|9+/)
# => ["111", "22", "3", "1", "33"]

Or:

s.scan(/((.)\2*)/).transpose[0]

Boy, are my fingers glad to save those keystrokes :)

andrew
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,574
Members
45,051
Latest member
CarleyMcCr

Latest Threads

Top