62,243
社区成员




string s = "select * from tableName where type=type1 oder by id DESC";
string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+([^\s]+)(?:\s+where\s*(.+)?(?:\s+group\s+by\s+(.+)\s+)?(?:\s+order\s+by\s+(.+)\s+)?)?$";
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[4].ToString();
string group = match.Groups[5].ToString();
this.message.Text = string.Format("{0}<br />{1}<br />{2}<br />{3}<br />{4}", n, fields, tableName, where, group);
}
string pattern = @"^select\s+(?:top\s+(\d+)\s+)?(.+)\s+from\s+(\w+)\s+(where\s(((?!(?:order|group))[\s\S])+))?((?:order|group) by .+)?$";
string s = "select * from tableName where type=type1 and type='order' order by id DESC";
TO:版主
貌似这样的SQL匹配不了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+", " ");
结果:
<br />fields=*<br />tableName=tableName<br />where=type=type1 <br />group=order by id DESCstring 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 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);
}