匹配不同字符串格式的字符串

时间:2012-10-23 14:53:08

标签: c# regex

我有一个带有长sql查询的随机.sql文件。我需要运行时从insert sql语句中获取所有表名以放入数组。如果insert语句在(一行)中,我可以得到表名(Inventory.tableA),如下所示:

...
Insert into Inventory.tableA;
...

但是,如果Insert语句有多行,例如下面的行,例如

Insert into 
Inventory.tableA;

OR

Insert into 
(blank line)
(blank line)
Inventory.tableA;

然后我检索表名的查询将失败。你能告诉我如何从长sql查询中获取表名,insert语句可以是一行还是多行?这里最好的方法是什么?

下面是我试过的可以处理1行的c#查询。

public List<string> GetAllTablesNames(string sp)
        {
            List<string> output = new List<string>();

            string[] contentSplit = sp.Split(new string[] { "INSERT INTO " }, StringSplitOptions.None);
            for (int a = 1; a < contentSplit.Length; a++)
            {
                string[] sa_tableName = contentSplit[a].Substring(0, contentSplit[a].IndexOf("\r")).Trim().Split('.');

                    output.Add(sa_tableName[0] + "." + sa_tableName[1]);
            }

            return output.Distinct().ToList();
        }

3 个答案:

答案 0 :(得分:2)

使用singleline模式

List<string> tables= Regex.Matches("yourInput",@"Insert into\s+(.*?)[\s\(]+"
,RegexOptions.Singleline|RegexOptions.IgnoreCase)
.Cast<Match>().Select(x=>x.Groups[1].Value)
.ToList<string>();

//tables contains all the table names

答案 1 :(得分:1)

我不确定你的正则表达是什么,但你可以:

  1. 将正则表达式中的所有空格更改为\s+
  2. 首先用" "替换所有结束,然后通过正则表达式运行。

答案 2 :(得分:1)

\ s将忽略所有空格,因此通过使用\ s +,它将跳过标签&amp; CRLF。由于你的例子有;,我们将捕获所有不是的文本;如果之间有空格,则改为使用[^; \ s] +。

string text = @"Insert into  
    Inventory.tableA;
    Insert into Orders;";

    var tableNames = Regex.Matches(text, @"(?:Insert into\s+)(?<Name>[^;]+)(?:;)")
                          .OfType<Match>()
                          .Select (mt => mt.Groups["Name"].Value);

    Console.WriteLine ("Tables: {0}", string.Join(" ", tableNames));            

    /* Tables: Inventory.tableA Orders */