日期:2014-05-19  浏览次数:20899 次

求正则表达式!
SELECT   FieldList   FROM   TableName   WHERE   ConditionList
根据上述语句获取FieldList,TableName,ConditionList,注:SELECT,FROM,WHERE不区分大小写,即:   解析出Select语句的字段列表,表名称,检索数据条件

------解决方案--------------------
string strSql= "SELECT FieldList FROM TableName WHERE ConditionList ";
egex reg=new Regex(@ "select\s+(? <select> \S.+\S)\s+from\s+(? <from> \S.+\S)\s+where\s+(? <where> \S.+\S) ",RegexOptions.IgnoreCase);
Match m=reg.Match(strSql);
string strSelect=m.Groups[ "select "].Value;
string strFrom=m.Groups[ "from "].Value;
string strWhere=m.Groups[ "where "].Value;
------解决方案--------------------
try

string yourStr = ..............;
string select = string .Empty;
string from = string .Empty;
string where = string .Empty ;
Match m = Regex.Match(yourStr, @ "select\s+(? <select> [\s\S]*?)\s+from\s+(? <from> ([^()]*?(\([^()]*\))*[^()]*?)+)\s+where\s+(? <where> [\s\S]*)$ ", RegexOptions.IgnoreCase);
if (m.Success)
{
select = m.Groups[ "select "].Value;
from = m.Groups[ "from "].Value;
where = m.Groups[ "where "].Value;
}

其实这个写的也不严谨,因为这样的需求需要考虑的情况太多,很难做到严谨,只能是有什么样的要求,就给什么样的正则了
------解决方案--------------------
用try,catch合适。try以下。不对了再说。
------解决方案--------------------
测试代码

string test = @ "SELECT 字段列表1 FROM
AA,
(SELECT 字段列表2 FROM BB WHERE 条件) BB
WHERE
AA.A=BB.B ";

string select = string.Empty;
string from = string.Empty;
string where = string.Empty;
Match m = Regex.Match(test, @ "select\s+(? <select> [\s\S]*?)\s+from\s+(? <from> ([^()]*?(\([^()]*\))*[^()]*?)+)\s+where\s+(? <where> [\s\S]*)$ ", RegexOptions.IgnoreCase);
if (m.Success)
{
select = m.Groups[ "select "].Value;
from = m.Groups[ "from "].Value;
where = m.Groups[ "where "].Value;
}

richTextBox2.Text += select + "\n\n ";
richTextBox2.Text += from + "\n\n ";
richTextBox2.Text += where + "\n\n ";

输出:

字段列表1

AA,
(SELECT 字段列表2 FROM BB WHERE 条件) BB

AA.A=BB.B

难道不符合你的要求吗?