我想将SQL INSERT语句解析为object(表示为文本)。有一个SQL脚本文件包含:
INSERT INTO Document(Id, Name, Description ...)
VALUES('DC001', 'FOO', 'bar');
INSERT INTO DocType(Id, Name)
VALUES('DT001', 'DOCX');
以及更多的表插入。
解析表名称(Document,DocType,..)的最简单方法是什么?
如果我不想计算子串,可以使用RegEx吗?
const string pattern = @"INSERT INTO\s\w";
foreach (var line in FileContent)
{
var a = Regex.Match(line, pattern, RegexOptions.Compiled | RegexOptions.IgnoreCase);
if (a.Success)
{
}
}
正则表达式做到了这一点
private readonly IList<string> _tableList = new List<string>();
public const string TableName = @"\s*(INSERT|UPDATE)\s*(INTO|\w+)\s*(\w+)\s*(\(|VALUES|SET)";
public static readonly Regex ValidLine = new Regex(TableName, RegexOptions.Compiled | RegexOptions.IgnoreCase);
var currentTableName = ValidLine.Match(line);
var value = currentTableName.Groups[3].Value;
if (!_tableList.Contains(value))
{
_tableList.Add(value);
}
我有类似的问题,解析SQL文件并在Ruby上提出这个通用的Parser。它涵盖了所有案例并将扫描结果记录到文件中以供进一步审核。也可以调整其他类型。 Take R10.rb file from here