开发者

Use Javascript RegEx to extract column names from SQLite Create Table SQL

开发者 https://www.devze.com 2022-12-29 17:25 出处:网络
I\'m trying to extract column names from a SQLite result set from sqlite_master\'s sql column. I get hosed up in the regular expressions in the match() and split() functions.

I'm trying to extract column names from a SQLite result set from sqlite_master's sql column. I get hosed up in the regular expressions in the match() and split() functions.

t1.executeSql('SELECT name, sql FROM sqlite_master WHERE type="table" and name!="__WebKitDatabaseInfoTable__";', [],
  function(t1, result) {
   for(i = 0;i < result.rows.length; i++){
     var tbl = result.rows.item(i).name;
     var dbSchema = result.rows.item(i).sql;
// errors out on next line
     var columns = dbSchema.match(/.*CREATE\s+TABLE\s+(\S+)\s+\((.*)\).*/)[2].split(/\s+[^,]+,?\s*/);
   }
  },
  function(){console.log('err1');}
);

I want to parse SQL statements like these...

CREATE TABLE sqlite_sequence(name,seq);
CREATE TABLE tblConfig (Key TEXT NOT NULL,Value TEXT NOT NULL);
CREAT开发者_运维百科E TABLE tblIcon (IconID INTEGER NOT NULL PRIMARY KEY,png TEXT NOT NULL,img32 TEXT NOT NULL,img64 TEXT NOT NULL,Version TEXT NOT NULL)

into a strings like theses...

name,seq
Key,Value
IconID,png,img32,img64,Version

Any help with a RegEx would be greatly appreciated.


Main problem is \s+ in your match regex. Should be /.*CREATE\s+TABLE\s+(\S+)\s*\((.*)\).*/)

Second problem is the split. I'm not quite sure what you tried to do in that regex, but here's a bit more straightforward way of doing it that does work on all of your examples:

var columns= dbSchema.match(/.*CREATE\s+TABLE\s+(\S+)\s*\((.*)\).*/)[2].split(/,/);
for(i = 0;i < columns.length; i++) {
    columns[i] = columns[i].replace(/\s.*/g, '');
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号