Pavan Pavan - 5 months ago 7
Ruby Question

How do I split this string in ruby to get the expected output in an array

I've this string

str = "Rs. 4,999Rs. 6,999Rs. 7,499Rs. 2,499Rs. 11,549Rs. 6,999Rs. 5,190Rs. 2,499Rs. 6,790Rs. 12,999Rs. 8,299Rs. 9,999Rs. 72,000Rs. 6,699Rs. 16,000Rs. 6,999Rs. 7,999Rs. 2,590Rs. 5,599Rs. 18,799"


How do I split this string to get my expected output in an array?

Expected output:

["Rs. 4,999", "Rs. 6,999", "Rs. 7,499", "Rs. 2,499", "Rs. 11,549", "Rs. 6,999", "Rs. 5,190", "Rs. 2,499", "Rs. 6,790", "Rs. 12,999", "Rs. 8,299", "Rs. 9,999" "Rs. 72,000", "Rs. 6,699", "Rs. 16,000", "Rs. 6,999", "Rs. 7,999", "Rs. 2,590", "Rs. 5,599", "Rs. 18,799"]


Below are my failed attempts

#1 with scan

str.scan(/.{1,9}/)

=> ["Rs. 4,999", "Rs. 6,999", "Rs. 7,499", "Rs. 2,499", "Rs. 11,54", "9Rs. 6,99", "9Rs. 5,19", "0Rs. 2,49", "9Rs. 6,79", "0Rs. 12,9", "99Rs. 8,2", "99Rs. 9,9", "99Rs. 72,", "000Rs. 6,", "699Rs. 16", ",000Rs. 6", ",999Rs. 7", ",999Rs. 2", ",590Rs. 5", ",599Rs. 1", "8,799"]


#2 with split

str.split(/Rs./).reject(&:empty?)
=> [" 4,999", " 6,999", " 7,499", " 2,499", " 11,549", " 6,999", " 5,190", " 2,499", " 6,790", " 12,999", " 8,299", " 9,999", " 72,000", " 6,699", " 16,000", " 6,999", " 7,999", " 2,590", " 5,599", " 18,799"]


I'm using ruby 2.2.3p173. Can anyone provide a solution for this?

Answer

Your scan attempt was the right way to go, but your data is incredibly regular. Instead of trying to match "1 to 9 of anything", match the literal parts and use a simple \d for the parts that are actually variable (the digits):

str.scan /Rs\. \d+,\d+/
=> ["Rs. 4,999", "Rs. 6,999", "Rs. 7,499", "Rs. 2,499", "Rs. 11,549", "Rs. 6,999", "Rs. 5,190", "Rs. 2,499", "Rs. 6,790", "Rs. 12,999", "Rs. 8,299", "Rs. 9,999", "Rs. 72,000", "Rs. 6,699", "Rs. 16,000", "Rs. 6,999", "Rs. 7,999", "Rs. 2,590", "Rs. 5,599", "Rs. 18,799"]