繁体   English   中英

从 C# 中的字符串中提取特定单词

[英]Extract specific words from a string in C#

虽然它在 pyhton 中很容易,但我是 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();
                   }
                }
            }

但是 output 也提供了很多其他词。 任何类型的铅都值得赞赏。

您可以尝试以下方法:

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 库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM