首页 > 解决方案 > 从 C# 中的字符串中提取特定单词

问题描述

虽然它在 python 中很容易,但我是 C# 新手,我无法从字符串中提取特定单词。我有两个 txt 文件。

abc.txt

select * from schema1.table1

xyz.txt

select * from schema2.table2 where a=5

我只需要提取“ schema1 ”和“ schema2 ”字,但我试过了,但我遇到了麻烦,因为它是 C#。

我的代码

            {
                StreamReader sr = new StreamReader(file);
                string data = sr.ReadLine();
                while (data != null)
                {
                string[] values = data.Split('.');
                foreach (string value in values)
                   {
                    Console.WriteLine(value.Split(' ').Last());
                    data = sr.ReadLine();
                   }
                }
            }

但是输出也给出了很多其他的词。任何一种铅都值得赞赏。

标签: c#oracle

解决方案


您可以尝试以下方法:

string sql = "select * from schema2.table2 where a=5";
var schema = Regex.Replace(sql, @"^select \* from ([^.]+)\.\S+.*$", "$1");
Console.WriteLine(schema);  // schema2

这个答案做了非常大的假设,包括您需要解析的每个 SQL 查询总是以select * from some_schema.some_table. 显然,对于更复杂/不同的查询,上述逻辑会失败。

通常,您可能需要找到一个可以解析 SQL 查询的 .NET 库。


推荐阅读