【问题标题】:How to find text in a text file using tags? [closed]如何使用标签在文本文件中查找文本? [关闭]
【发布时间】:2020-07-10 00:57:35
【问题描述】:
我有一个从 C# 代码 sn-p 创建的文件,该文本文件的结构如下:
#File
[ASSETS]
[VARIABLES]
i: 0
然后,在同一个文件中,写入以下行:
#File
[ASSETS]
"Image.png">C:\Users\User\Desktop\Image.png
"mine.gif"C:\Users\User\Desktop\mine.gif
[VARIABLES]
i: 0
现在我要做的是找到标签“[ASSETS]”内的文本,我该怎么做?
【问题讨论】:
-
Stack Overflow 不是一个“写代码 4 我”的网站。一个问题应该包括一个很好的minimal reproducible example,它显示了您已经尝试过的内容,以及该代码的作用的详细说明,它与您想要的有何不同,以及您具体是什么需要帮助。就目前而言,您的问题太宽泛了。
标签:
c#
file
text
text-files
【解决方案1】:
正如其他人所提到的,您选择的文件格式不是很好,但是按照您的决定,您可以做这样的事情。未经测试,但我会留给您解决我的任何错误、忽略空格或空行、想出更有效的解决方案等。
string[] lines = File.ReadAllLines("file.txt"); //read file content
int index = lines.IndexOf("[ASSETS]");//get index of assets tag
var assets = new List<string>(); // create variable to store asset lines
while (index != -1 && ++index < lines.Length && !lines[index].StartsWith("[")) // as long as we had found the assets tag, the next line exists, and the next line isn't a tag (presumably only lines that start with [ are tag lines...) then add the next line to your assets list
{
assets.Add(lines[index]);
}
Console.WriteLine(string.Join(Environment.NewLine, assets)); // demonstrate successful asset collection
【解决方案2】:
如果启用单行和多行,这个正则表达式应该可以完成这项工作
^\[ASSETS\](.+)^\[
你会在第一个捕获组中找到字符串
例如,您可以阅读有关 C# 正则表达式 here 的更多信息