[英]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? 我如何以相当干净的方式使用Ruby和/或regex完成此操作? 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. 我对编程很陌生,做了很多贫民窟的事情,例如数组到字符串返回到数组的转换,.reverse.chomp.reverse恶作剧,但最终还是无法获得想要的结果。 Help appreciated! 帮助赞赏!
Try scan
with a regexp: 尝试使用正则表达式进行scan
:
array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array = array.first.scan(/:?(\w+)[,\\n]/).flatten
p array
#=> ["dputnam", "kmathise", "hhoang3", "nhalvors", "jchildre"]
以下将为您提供预期的结果:
array2 = array[0].split(':').last.gsub(/\\n\Z/, '').split(',')
I would do 我会做
array = [ 'c32860:x:3105:dputnam,kmathise,hhoang3,nhalvors,jchildre\n' ]
array[0].scan(/(?<=:)?\w+(?=[,\\n])/)
# => ["dputnam", "kmathise", "hhoang3", "nhalvors",'jchildre' ]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.