KyuuQ
KyuuQ

Reputation: 65

Using regex or Ruby functions to select elements after a certain string

I have an array with a single element shown below:

array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]

I want to create a new array that looks like this:

array2 = [ 'dputnum', 'kmathise', 'hhoang3', 'nhalvors', 'jchildre' ]

How would I accomplish this using Ruby and/or regex in a fairly clean way? I'm very new to programming and I did a bunch of ghetto things such as array-to-string-back-to-array conversions, .reverse.chomp.reverse shenanigans, and still could not end up with the result I wanted. Help appreciated!

Upvotes: 0

Views: 47

Answers (3)

Arup Rakshit
Arup Rakshit

Reputation: 118271

I would do

array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array[0].scan(/(?<=:)?\w+(?=[,\\n])/)
# => ["dputnam", "kmathise", "hhoang3", "nhalvors",'jchildre' ]

Upvotes: 0

jmromer
jmromer

Reputation: 2236

Try scan with a regexp:

array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array = array.first.scan(/:?(\w+)[,\\n]/).flatten

p array
#=> ["dputnam", "kmathise", "hhoang3", "nhalvors", "jchildre"]

Upvotes: 1

xdazz
xdazz

Reputation: 160863

Below will give you the expected result:

array2 = array[0].split(':').last.gsub(/\\n\Z/, '').split(',')

Upvotes: 0

Related Questions