c# - 从 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();
}
}
}
但是输出也给出了很多其他的词。任何一种铅都值得赞赏。
解决方案
您可以尝试以下方法:
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 库。
推荐阅读
- rest - RabbitMQ 事件订阅者 - 哪个好?Windows 服务或 Http 服务 (REST API)
- spring-boot - Thymeleaf 中的 @{..} 表达式是什么
- javascript - 计算字符串中的单词出现次数 javascript
- c++ - 如何在 Debian Wheezy 中编译 Mono
- javascript - 如何获取光标存在于可内容编辑的 div 中的 div?
- go - 带有和不带有空白标识符的 Golang 计时
- plot - Gnuplot:是否可以跳过以给定字符开头的标题行?
- r - 如何编写一个计算变量之间相关性的函数
- html - 检测是否
- go - 我可以为另一个域指定和设置 http-only cookie 吗?