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);
 
}

解决方案 »

  1.   

    s = Regex.Replace(s, @"\s+", " ");结果:<br />fields=*<br />tableName=tableName<br />where=type=type1 <br />group=order by id DESC
      

  2.   

    update:string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+(\w+)\s+(where\s(((?!(?:order|group)).)+))?((?:order|group) by .+)?$";
      

  3.   

    string s = "select * from tableName where type=type1 and type='order' order by id DESC";TO:版主
    貌似这样的SQL匹配不了
      

  4.   

    这是单引号没有匹配到的原因,try:string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+(\w+)\s+(where\s(((?!(?:order|group))[\s\S])+))?((?:order|group) by .+)?$";
      

  5.   

    string s = "select * from tableName where type=type1 and type='order' order by id DESC";
    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);
     
    }