将变量保存在从特定点开始的行中

时间:2018-01-05 08:45:40

标签: c# regex

C#程序扫描大型.txt文件以查找特定模式,例如: G。的ProcessID。如果找到此模式,则应将以下ID写入变量。

我使用StreamReader和方法ReadLine分别扫描每一行。 我的问题是如果System.Text.RegularExpressions.Regex.IsMatch(line, processID)在某个点之前为真,我如何保存该值?

这是到目前为止的代码:

String path = "C:\\Users\\myfile.txt", line = null, getID = null, ram = null;

String IDPattern = "^\\d{5}-\\d{6}$";
System.IO.StreamReader file = new System.IO.StreamReader(@path);

while ((line = file.ReadLine()) != null)
{
    if(line.Contains("--Process-ID="))
    {

        // ram = How does ram gets the value?!

        if(getID != ram)
        {
            getID = ram;
            Console.WriteLine(getID);
        }
    }
}

变量ram用于临时保存值并将其与getID进行比较。

2 个答案:

答案 0 :(得分:2)

您可以使用捕获组。试试这段代码

var regex = new Regex("--Process-ID=(?<id>\\d{5}-\\d{6})");
string processID;
using (var reader = new StreamReader(File.OpenRead("C:\\Users\\myfile.txt")))
{
    while (true)
    {
        var nextLine = reader.ReadLine();
        if (nextLine == null)
            break;

        var match = regex.Match(nextLine);
        if (match.Success)
        {
            processID = match.Groups["id"].Value;
            break;
        }
    }
}

当正则表达式找到第一个匹配时,它会将其保存到局部变量并跳过文件的其余部分。

答案 1 :(得分:0)

你可以使用File类并使用类似的东西来实现你的目标。

 IList<string> text = new List<string>() { "pid456","Pid 123" }; //Place your pid here
 var endTag = "xyz"; //end tag of tag file or EOF

            IList<string> log = File.ReadAllLines(file).ToList<string>();

            for (int i = log.Count - 1; i > 0; i--)
            {
                if (text.Any(t => log[i].Contains(t)))
                {
                   var PID= log[i];
                }

                if (log[i].Contains(endTag))
                {
                    break;
                }
             }