嘿,我只想知道是否有人有一个REGEX可以接受这样的查询:
SELECT pillers, Balloons, Tacks FROM the_database_file WHERE Balloons != 'small' AND Balloons != 'large'把它格式化成这样:
SELECT pillers, Balloons, Tacks
FROM the_database_file
WHERE Balloons != 'small'
AND Balloons != 'large'我一直在四处寻找,我所能找到的就是找到一个GO或类似的东西来启动拆分,这一点也帮不了我。此外,select语句还可以包含或或更多的和,上面只是我将运行的这样一个查询的一个例子。
发布于 2016-02-17 16:50:15
请说明格式化SQL查询的目的是什么?有太多的在线和离线工具可以用来格式化SQL查询。所以我想知道你为什么要用Regex :)
喜欢
发布于 2016-02-17 18:28:35
您可以创建一个regex表达式来捕获组中的SELECT、FROM和WHERE部分,并使用Regex.Replace()方法创建一个新的字符串,如下所示:
SELECT pillers, Balloons, Tacks
FROM the_database_file
WHERE Balloons != 'small' AND Balloons != 'large'这是代码:
var sql = "SELECT pillers, Balloons, Tacks FROM the_database_file WHERE Balloons != 'small' AND Balloons != 'large'";
string pattern = "^(?<select>SELECT\\s+[\\w\\*\\.]+(?:[\\s\\,]+[\\w\\*\\.]+)*)\\s+(?<from>FROM\\s+\\w+)\\s+(?<where>(WHERE\\s+.+?)(\\s+(?:AND|OR)\\s+.+?)*)$";
var result = Regex.Replace(sql, pattern, "${select}\n${from}\n${where}");我认为您不能为每个条件创建一条线,因为您无法获得同一捕获组的所有匹配。
但你可以这样做:
var sql = "SELECT pillers, Balloons, Tacks FROM the_database_file WHERE Balloons != 'small' AND Balloons != 'large'";
string pattern = "^(?<select>SELECT\\s+[\\w\\*\\.]+(?:[\\s\\,]+[\\w\\*\\.]+)*)\\s+(?<from>FROM\\s+\\w+)\\s+(?<where>(WHERE\\s+.+?)(\\s+(?:AND|OR)\\s+.+?)*)$";
Regex regex = new Regex(pattern);
var match = regex.Match(sql);
var all = match.Groups[0];
var select = match.Groups["select"];
var from = match.Groups["from"];
var where = match.Groups["where"];
var conditions = match.Groups.Cast<Group>().Except(new Group[] { all, select, from, where });
string result = string.Format("{0}\n{1}\n{2}", select.Value, from.Value, string.Join("\n", conditions.Select(c => c.Value.Trim())));
Console.WriteLine(result);可以从组中排除第一个组、SELECT组、from组和WHERE组,其余组将是查询条件。
这就是你得到的
SELECT pillers, Balloons, Tacks
FROM the_database_file
WHERE Balloons != 'small'
AND Balloons != 'large'https://stackoverflow.com/questions/35462503
复制相似问题