问题:
从一行 SQL 脚本中提取表名和列名:
CREATE TABLE [ dbo ] . [ worktype_template ] ( [ worktype_key ] [ int ] NULL , [ template_key ] [ int ] NULL ) ON [ PRIMARY ]
我已经尝试了许多正则表达式,但都失败了。任何建议,尤其是 C# 中的建议,都会有所帮助。
这有效:
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;
我希望它有所帮助。