user1570144
user1570144

Reputation: 479

Split string without removing delimiter

I need to parse a file to get individual SQL statements and run them from rails controller.

I have the following code:

@sql_file = "#{RAILS_ROOT}/lib/evidence_interface_import.sql"   
@sql_stmts_array = File.read(@sql_file).split(";")  

@sql_stmts_array.each_with_index do |sql_stmt,s_index|
   ActiveRecord::Base.connection.execute(sql_stmt)
end

The split removes the ";" from the end of the SQLs. Is there a way not to remove the ";" and still split using ";".

Upvotes: 11

Views: 8287

Answers (5)

Andrew Marshall
Andrew Marshall

Reputation: 96914

Yup, scan it:

'a; b; c;'.scan(/[^;]*;/)
#=> ["a;", " b;", " c;"]

You could get rid of the excess whitespace by tacking on map(&:strip) after, but it's probably not needed here.

Note that this is very rudimentary, and something like a string literal in the SQL with a semicolon in it will break this. (E.g. select * from stuff where name = ";";.)

Upvotes: 16

maljub01
maljub01

Reputation: 384

When using ActiveRecord::Base.connection.execute you don't need to include the semicolon in the first place.

Also, another way to split without removing the delimiter is to use groups as shown in the following example:

"a;b;c".split(/;/)   # => ["a", "b", "c"]

"a;b;c".split(/(;)/) # => ["a", ";", "b", ";", "c"]

Upvotes: 9

user1570144
user1570144

Reputation: 479

This works:

@sql_stmts_array = File.read(@sql_file).lines(separator=';')

Upvotes: 4

sawa
sawa

Reputation: 168081

Use a regex with a lookbehind

split(/(?<=;)/)

Upvotes: 6

siame
siame

Reputation: 8657

You could try using scan with an appropriate regex, which should give you results similar to split, but if you want to stick to a way without regex, you can just append a semi-colon to each cell in the array:

@sql_stmts_array = File.read(@sql_file).split(";").each do |s|
  s << ";"
end

Upvotes: 1

Related Questions