Split string on a number, preserving the number
I have a string which will alway开发者_JAVA百科s 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?
String#split
will keep any groups from the delimiter regexp in the result array.
parts = whole.split(/(\d+)/)
In case you didn't really want the whitespace in the separators, and you did want to have a consistent handle on the before/after, use this:
test = [
"4",
"Section 2",
"4 Section",
"Section 5 Aisle",
]
require 'pp'
pp test.map{ |str| str.split(/\s*(\d+)\s*/,-1) }
#=> [["", "4", ""],
#=> ["Section", "2", ""],
#=> ["", "4", "Section"],
#=> ["Section", "5", "Aisle"]]
Thus you could always do:
prefix, digits, suffix = str.split(/\s*(\d+)\s*/,-1)
if prefix.empty?
...
end
...instead of testing the length of your matches or some such.
精彩评论