根据特定格式搜索字符串

本文关键字:搜索 字符串 格式 定格 | 更新日期: 2023-09-27 17:56:43

我在搜索某些格式的文本时遇到问题。 我的文件如下所示。

britney     ak4564gc1    18
scott       ak3333hc2    28
jenny       ad4564gc3    32
amy         ak4564gc4    29

我想搜索具有某种动态格式的工作编号。 这是我的代码。 格式必须具有特定的长度,其中 * 作为更改变量。

for (int line = 0; line <= Countline(OriFile)-1; line++)
{
    var desiredText = File.ReadAllLines(OriFile).ElementAt(line);
    string s = desiredText.ToString();
    string b = s.Substring(WONUmStart, WONumLength);
    //format changeable(I changed it to make it easier to understand)
    if(b.Contains(a.TextBox.ToString())) //textbox value "ak****gc*"
    {
        if (WoNum != b)
        {
            WoNum = b;
            StreamWriter sw = new StreamWriter(reportfile, true);
            sw.WriteLine(Path.GetFileName(OriFile) + 
                         " " + 
                         WoNum + 
                         "   " + 
                         Path.GetFileName(MergeFile));
            sw.Flush();
            sw.Close();
        }
    }
}

有人可以指导我吗?

根据特定格式搜索字符串

我建议在Linq中使用正则表达式,例如

string pattern = @"'bak.{3}gc.{1}'b";
var result = File
  .ReadLines(OriFile)
  .Select(line => Regex.Match(line, pattern)) // if we expect at most one match per line 
  .Where(match => match.Success)
  .Select(match => match.Value);  
 ...
File.WriteAllLines(reportfile, result.
  Select(line => string.Format("{0} {1}   {2}", 
    Path.GetFileName(OriFile), line, Path.GetFileName(MergeFile))));