我知道这是一个非常古老且基本的问题,但就我而言,这有点不同。
问题:我有一个包含如下数据的字符串。
select * from table1; select col1,col2,col5 from table2; select col8 from table3;
我需要从上面的字符串中找到一个列列表和一个表名。
我用.lastIndexOf() and .SubString()
尝试过,但是没有给出我想要的确切输出。
所需的输出:
应该如何提取以上数据?
答案 0 :(得分:1)
您可以使用以下代码:
string storedProcContent = "select * from table1; select col1,col2,col5 from table2; select col8 from table3;";
Regex rx = new Regex(@"select ([\w,\*]+?) from ([\w]+)", RegexOptions.IgnoreCase|RegexOptions.Compiled);
MatchCollection matches = rx.Matches(storedProcContent);
Console.WriteLine("{0} matches found in:\n {1}",
matches.Count, storedProcContent);
foreach (Match match in matches)
{
GroupCollection groups = match.Groups;
Console.WriteLine("Table name = {0}", groups[2].Value);
Console.WriteLine("Column Used = {0}", groups[1].Value);
}
输出:
3 matches found in:
select * from table1; select col1,col2,col5 from table2; select col8 from table3;
Table name = table1
Column Used = *
Table name = table2
Column Used = col1,col2,col5
Table name = table3
Column Used = col8