简体   繁体   English

C#-RegEx-获取两行之间的字符串

[英]C# - RegEx - Get Strings Between Two Lines

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#? 问题:如何在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. 问题:我使用了网站“ RegExr”和“ Regex101”,该网站显示应该在“ Groups [1]”中捕获处理器名称,但是在尝试将其转储到消息框中时似乎没有捕获任何处理器。

Any advice would be greatly appreciated! 任何建议将不胜感激!

Thank you! 谢谢!

Change your code to read all of the file into a single string variable and then run the Regex against that: 更改您的代码以将所有文件读入单个字符串变量,然后对此运行Regex:

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM