Divide a string by a number, keeping the number

I have a line that 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 line as follows:

 "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?

+8
ruby regex
source share
2 answers

String#split will contain any groups from the regexp separator in the result array.

 parts = whole.split(/(\d+)/) 
+18
source share

If you really don't need spaces in delimiters, and you want to have a consistent handle before and 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 can always:

 prefix, digits, suffix = str.split(/\s*(\d+)\s*/,-1) if prefix.empty? ... end 

... instead of checking the length of your matches or some.

+2
source share

Source: https://habr.com/ru/post/651365/


All Articles