Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 ";".

like image 590
user1570144 Avatar asked Sep 22 '12 00:09

user1570144


People also ask

Does string split remove delimiter?

split() is a powerful string manipulation tool that we have at our disposal, but it can also be destructive. Splitting will remove delimiters from the returned array, which may give us output that differs greatly from what the original string was.

How do you split a string with a delimiter?

Using String. split() Method. The split() method of the String class is used to split a string into an array of String objects based on the specified delimiter that matches the regular expression.


2 Answers

Use a regex with a lookbehind

split(/(?<=;)/)
like image 69
sawa Avatar answered Sep 27 '22 20:09

sawa


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 = ";";.)

like image 26
Andrew Marshall Avatar answered Sep 27 '22 20:09

Andrew Marshall