1

I've been battling with this question for a couple of days now.

Question: How can I pull multiple strings that match my search criteria between two lines in C#?

Here is my current process:

  1. Read all lines of a file.

    text_file = "C:\test.txt";
    string[] file_text = File.ReadAllLines(text_file);
    
  2. Loop through each line of the file and search for matches

    foreach (string line in file_text)
    {
        Regex r1 = new Regex(@"Processor\(s\):\s+.+\n\s+(.+)\nBIOS Version:");
    
        Match match1 = r1.Match(line);
    
        if (match1.Success)
        {
            string processor = match1.Groups[1].Value;
            // Just to see if I matched anything
            System.Windows.MessageBox.Show(processor);
        }
    }
    
  3. Here is the example text:

    Processor(s):              1 Processor(s) Installed.
                               [01]: Intel64 Family 6 Model 23 Stepping 10 GenuineIntel ~2826 Mhz
    BIOS Version:              Phoenix Technologies LTD 6.00, 7/30/2013
    

Problem: I used the website "RegExr" and "Regex101" which shows that the processor name should be captured in "Groups[1]" but nothing appears to be captured when I attempt to dump it to a message box.

Any advice would be greatly appreciated!

Thank you!

1
  • 3
    You read the files into a line array, and use a regex to match several lines. This is impossible that way. If you want to read a whole file in, read it all into a variable, and use your regex on the whole text with newlines. Commented Mar 24, 2016 at 15:49

1 Answer 1

2

Change your code to read all of the file into a single string variable and then run the Regex against that:

text_file = "C:\test.txt";
string file_text = File.ReadAllText(text_file);

Regex r1 = new Regex(@"Processor\(s\):\s+.+\n\s+(.+)\nBIOS Version:");

Match match1 = r1.Match(file_text);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I followed Wiktor and your advice and I'm able to pull data! The only problem I'm facing is that it only grabs one match, instead of all the matches. Trying to figure that out now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.