BTW: 你的SQL语句有问题 : oder ==> order
string s = "select * from tableName where type=type1 order by id DESC";
string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+(\w+)\s+(where\s(((?!(?:order|group)).)+))?((?:order|group) by .+$)";
s = Regex.Replace(s, @"\s{2,}", " ");
s = s.Replace(", ", ",").Trim();
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
var match = reg.Match(s);
if (match.Success)
{
string n = match.Groups[1].ToString();
string fields = match.Groups[2].ToString();
string tableName = match.Groups[3].ToString();
string where = match.Groups[5].ToString();
string group = match.Groups[7].ToString();
string result=string.Format("{0}<br />fields={1}<br />tableName={2}<br />where={3}<br />group={4}", n, fields, tableName, where, group);
}
string s = "select * from tableName where type=type1 order by id DESC";
string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+(\w+)\s+(where\s(((?!(?:order|group)).)+))?((?:order|group) by .+$)";
s = Regex.Replace(s, @"\s{2,}", " ");
s = s.Replace(", ", ",").Trim();
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
var match = reg.Match(s);
if (match.Success)
{
string n = match.Groups[1].ToString();
string fields = match.Groups[2].ToString();
string tableName = match.Groups[3].ToString();
string where = match.Groups[5].ToString();
string group = match.Groups[7].ToString();
string result=string.Format("{0}<br />fields={1}<br />tableName={2}<br />where={3}<br />group={4}", n, fields, tableName, where, group);
}
貌似这样的SQL匹配不了
string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+(\w+)\s*(where\s(((?!(?:order|group) by)[\s\S'])+))?((?:order|group) by .+)?$";
s = Regex.Replace(s, @"\s+", " ");
s = s.Replace(", ", ",").Trim();
Regex reg = new Regex(pattern, RegexOptions.IgnoreCase);
var match = reg.Match(s);
if (match.Success)
{
string n = match.Groups[1].ToString();
string fields = match.Groups[2].ToString();
string tableName = match.Groups[3].ToString();
string where = match.Groups[5].ToString();
string group = match.Groups[7].ToString();
string result=string.Format("{0}<br />fields={1}<br />tableName={2}<br />where={3}<br />group={4}", n, fields, tableName, where, group);
}