从正则表达式的hashset中抓取行和前一行

时间:2013-09-06 18:04:45

标签: regex vb.net

我想要完成的是一个包含以下内容的哈希集:

MSI (c) (AC:C0) [14:23:21:685]: Back from server. Return value: 1603
MSI (c) (AC:C0) [14:23:21:685]: Decrementing counter to disable shutdown. If counter >= 0, shutdown will be denied.  Counter after decrement: -1
MSI (c) (AC:C0) [14:23:21:685]: PROPERTY CHANGE: Deleting SECONDSEQUENCE property. Its current value is '1'.
Action ended 14:23:21: ExecuteAction. Return value 3.
MSI (c) (AC:C0) [14:23:21:685]: Doing action: SetupCompleteError
Action 14:23:21: SetupCompleteError. 
Action start 14:23:21: SetupCompleteError.

找到返回值3时;线和&它之前的行应该添加到第二个hashset。

MSI (c) (AC:C0) [14:23:21:685]: PROPERTY CHANGE: Deleting SECONDSEQUENCE property. Its current value is '1'.
Action ended 14:23:21: ExecuteAction. Return value 3.)

这可以作为正则表达式找到该行和上面的行(据我所知)但到目前为止,我试图将两行移动到下一个散列集的所有内容只移动包含返回值3的行。

    Dim regrv3 As New Regex("(.*)\S\s(.*)Return value 3.")

相关代码:

Dim opened As New HashSet(Of String)(File.ReadAllLines(openfile))
Dim compa As HashSet(Of String) = New HashSet(Of String)

For Each StringMatch In opened
    Dim m As Match
    m = regrv3.Match(StringMatch)
    compa.Add(m.ToString
Next

我错过了一些明显的东西,还是需要某种复杂的索引才能执行此操作?

1 个答案:

答案 0 :(得分:1)

我还没有收到你的回复,所以我假设"返回值3"并且前一行应被视为hashset中的一个条目。此解决方案不使用正则表达式,但这应该可以实现您的目标并仍然产生一个哈希集结果。

Dim inputLines = File.ReadAllLines(filepath)
Dim matches As New HashSet(Of String)

For i = 0 To inputLines.Length - 1
  If inputLines(i).Contains("Return value 3.")
    'Okay we found what we're looking for, combine with previous line
    'Btw... there's an exception hidden here (hint: when i=0)
    Dim match = inputLines(i - 1) & inputLines(i)
    matches.Add(match)
  EndIf
Next