简体   繁体   中英

splitting a string in ruby 1.9.2

I have a string something like this

JINSAL0056(  1), JINSAL0057(  1), JINSAL0041(  1),

I need to put JINSAL0056, JINSAL0057,JINSAL0041 in a field and number inside the (). I have written couple of codes let me know if I am going in the right directions.

s = "JINSAL0056(  1), JINSAL0057(  1), JINSAL0041(  1)"
ss = s.split(",")
sss = ss.split(" ( ")

How to write the split. Please do help me put

You can pass regexes to split too:

foo = "JINSAL0056(  1), JINSAL0057(  1), JINSAL0041(  1),"
foo.split(/[\(\),\s]+/)

The result:

["JINSAL0056", "1", "JINSAL0057", "1", "JINSAL0041", "1"]

And make it into a hash:

Hash[*foo.split(/[\(\),\s]+/)]

Which will give you:

{"JINSAL0056"=>"1", "JINSAL0057"=>"1", "JINSAL0041"=>"1"}

I think you can try. (Not the best way of course.)

yourstring = "JINSAL0056(  1), JINSAL0057(  1), JINSAL0041(  1),"
yourstring.split(/(\w+)\(\s*(\d)\)[,\s*]/)

Result will be

["", "JINSAL0056", "1", " ", "JINSAL0057", "1", " ", "JINSAL0041", "1"]

but I recommended to use scan(//)

yourstring.scan(/(\w+)\(\s*(\d)\)[,\s*]/)

Result will be

[["JINSAL0056", "1"], ["JINSAL0057", "1"], ["JINSAL0041", "1"]]

to assign variable you can loop like this

yourstring.scan(/(\w+)\(\s*(\d)\)[,\s*]/).each do |a,b|
     puts "#{a} #{b}"
end
s = "JINSAL0056(  1), JINSAL0057(  1), JINSAL0041(  1)"
res = s.split(', ').map{|line| line.chop.split('(  ')}
p res # [["JINSAL0056", "1"], ["JINSAL0057", "1"], ["JINSAL0041", "1"]]

res.each do |jinsal, number|
  puts "Do something with #{jinsal} and #{number}"
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM