我有一个包含许多信息的文本文件,但是我只想显示该文本文件的序列号。我能够读取并在标签中显示序列号的整行,但是我只需要[[BcXXXXX“]格式的序列号。任何人都可以指导吗?
string path = @"D:\Sample.txt";
StringBuilder buffer = new StringBuilder();
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
String str = sr.ReadLine();
if (Regex.IsMatch(str, "Bc"))
buffer.Append(str);
string s = buffer.Append(str);
int start = s.IndexOf("["Bc") + 1;
int end = s.IndexOf(""]" , start);
string result = s.Substring(start, end - start);
label2.Text = result.ToString();
}
答案 0 :(得分:0)
string serialNumber = System.IO.File.ReadLines(@"D:\Sample.txt")
.Select(line =>
{
var match = System.Text.RegularExpressions.Regex.Match(line, @"^\[""(.*)""\]$");
return match.Success ? match.Groups[1].Value : null;
}).FirstOrDefault(sn => sn != null);