Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string on a number, preserving the number

Tags:

regex

ruby

I have a string which will always be at least a number, but can also contain letters before and/or after the number:

"4"
"Section 2"
"4 Section"
"Section 5 Aisle"

I need to split the string like this:

"4" becomes "4"
"Section 2" becomes "Section ","2"
"4 Aisle" becomes "4"," Aisle"
"Section 5 Aisle" becomes "Section ","5"," Aisle"

How can I do this with Ruby 1.9.2?

like image 364
ben Avatar asked Jan 22 '11 05:01

ben


People also ask

How do you split a number string?

To split a string into a list of integers: Use the str. split() method to split the string into a list of strings. Use the map() function to convert each string into an integer.

How do you split a numeric string in Python?

The split() method of the string class is fairly straightforward. It splits the string, given a delimiter, and returns a list consisting of the elements split out from the string. By default, the delimiter is set to a whitespace - so if you omit the delimiter argument, your string will be split on each whitespace.


1 Answers

String#split will keep any groups from the delimiter regexp in the result array.

parts = whole.split(/(\d+)/)
like image 162
outis Avatar answered Oct 16 '22 01:10

outis