使用C#从SQL CREATE脚本中提取表名和列名

时间:2013-10-22 14:13:52

标签: c# sql regex

问题:

从一行SQL脚本中提取表名和列名:

CREATE TABLE [ dbo ] . [ worktype_template ] ( [ worktype_key ] [ int ] NULL , [ template_key ] [ int ] NULL ) ON [ PRIMARY ]

我尝试了很多正则表达式,并且悲惨地失败了。任何建议,特别是在C#中,都会有所帮助。

1 个答案:

答案 0 :(得分:0)

这有效:

String query = "CREATE TABLE [ dbo ] . [ worktype_template ] ( [ worktype_key ] [ int ] NULL , [ template_key ] [ int ] NULL ) ON [ PRIMARY ]";
query = query.Replace(" . ", ".");
query = query.Replace("[ ", "[");
query = query.Replace(" ]", "]");
// Selects what is between parenthesizes 
String fieldsString = new String(query.SkipWhile(c => c != '(').TakeWhile(c => c != ')').ToArray());
// Selects the fields
String[] fields = fieldsString.Split(',').Select(line => new Regex("\\[\\w+\\]").Match(line).Value).ToArray();
// Selects table name
String tableName = new Regex("\\[\\w+\\](\\.\\[\\w+\\])*").Match(query).Value;

我希望它有所帮助。