tags:

views:

70

answers:

2

I have a string I want to split: D017209D019169D019014 into D017209, D019169, and D019014 with commas in between.

If I have

a = D017209D019169D019014
b = a.slice("D")
puts b

My result looks like:

017209
019169
019014

What am I missing?

A: 

a string split function will always remove the terminator. You want to substrings that begin with 'D'. A regex would be best here

a.scan(/D[0-9]*/).each do |line|
  #do stuff with each piece of data
end

BTW, as I said in my comment I am absolutely NOT a regex expert, not even good really. So, if someone finds a gaping whole in this let me know, but it should work with the input you have.

Ed Swangren
+5  A: 
"D017209D019169D019014".scan(/D[^D]*/)

Scan returns an array of all the matches, which is exactly what you want here. The regex simply means D, followed by zero or more non-D's.

Matthew Flaschen
Add a join adds in the commas"D017209D019169D019014".scan(/D[^D]*/).join(",") yields"D017209,DD019169,DD019014"
Paul Rubel