.net - 正则表达式 - 重复组

标签 .net regex

我正在尝试读取日志文件并使用正则表达式提取一些机器/设置信息。以下是日志中的示例:

...
COMPUTER INFO:
 Computer Name:                 TESTCMP02
 Windows User Name:             testUser99
 Time Since Last Reboot:        405 Minutes
 Processor:                     (2 processors) Intel(R) Xeon(R) CPU            5160  @ 3.00GHz
 OS Version:                    5.1 .number 2600:Service Pack 2
 Memory:                        RAM: 48% used, 3069.6 MB total, 1567.3 MB free
 ServerTimeOffSet:              -146 Seconds 
 Use Local Time for Log:        True

INITIAL SETTINGS:
 Command Line:                  /SKIPUPDATES
 Remote Online:                 True
 INI File:                      c:\demoapp\system\DEMOAPP.INI
 DatabaseName:                  testdb
 SQL Server:                    10.254.58.1
 SQL UserName:                  SQLUser
 ODBC Source:                   TestODBC
 Dynamic ODBC (not defined):    True
...

我想捕获每个“数据块”,使用标题作为一组,将数据作为第二组(即“计算机信息”,“计算机名称:.......”)并为每个重复此操作堵塞。到目前为止,如果有的表达式是
(?s)(\p{Lu}{1,} \p{Lu}{1,}:\r\n)(.*\r\n\r\n)

这会像它应该的那样将块拉到组中,这很棒。但我需要让它重复捕获,我似乎无法得到。我尝试了几种分组表达式,包括:
(?s)(?:(\p{Lu}{1,} \p{Lu}{1,}:\r\n)(.*\r\n\r\n))*

这似乎是正确的,但我得到了很多带有空组项目值的 NULL 结果组。我正在使用 .Net RegEx 类来应用表达式,有人可以帮我吗?

最佳答案

不可能有重复的组。该组将包含最后一场比赛。

您需要将其分解为两个问题。首先,找到每个部分:

new Regex(@"(?>^[A-Z\s]+:\s*$)\s*(?:(?!^\S).)*", RegexOptions.Singleline | RegexOptions.Multiline);

然后,在每个匹配项中,使用另一个正则表达式将每个字段/值匹配到组中:
new Regex(@"^\s+(?<name>[^:]*):\s*(?<value>.*)$", RegexOptions.Multiline);

使用它的代码如下所示:
Regex sectionRegex = new Regex(@"(?>^[A-Z\s]+:\s*$)\s*(?:(?!^\S).)*", RegexOptions.Singleline | RegexOptions.Multiline);
Regex nameValueRegex = new Regex(@"^\s+(?<name>[^:]*):\s*(?<value>.*)$", RegexOptions.Multiline);
MatchCollection sections = sectionRegex.Matches(logData);
foreach (Match section in sections)
{
    MatchCollection nameValues = nameValueRegex.Matches(section.ToString());
    foreach (Match nameValue in nameValues)
    {
        string name = nameValue.Groups["name"].Value;
        string value = nameValue.Groups["value"].Value;
        // OK, do something here.
    }
}

关于.net - 正则表达式 - 重复组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1689325/

相关文章:

c# - 设置纸张尺寸

c# - 使用 C# 和 .NET 2.0 创建顺序文件夹名称?

.net - 为非 VB6 人员挑选一个 VB6 项目

regex - 如何用正则表达式捕获字符串 "word1/word2/*"?

c# - 如何匹配来自 Firefox 浏览器的正则表达式中的句点?

java - 使用正则表达式拆分字符串\w\w*?\w+?

Python 正则表达式引用与替换编号冲突

c# - 防止 Resharper "Possible Null Reference Exception"警告

.net - 为什么我的 Direct2D 绘图性能如此糟糕?

php - 替换以 # 开头的占位符,然后是整个单词