对字符串执行多个正则表达式

时间:2015-01-03 02:16:38

标签: regex vba

我的日志文件大约是15mb,而且我是从前员工的解析器构建的。

我想弄清楚的是,是否可以针对字符串执行多个(3个不同的)正则表达式。我希望将其缩减为一个宏以节省处理时间,而不是针对相同的日志文件运行3个不同的宏。

相关守则:

Dim regEx, Match, Matches
Dim text1 As String
Dim text2 As String
Dim text3 As String
Dim text4 As String
Dim text5 As String
Dim text6 As String
Set regEx = New RegExp  ' Create a regular expression.
regEx.Pattern = "(?:user:\s.)(\w*)(?:].*\n.*\n.*\n.*\.*\n\s*.*\n)(\d*:\d*:\d*\.\d*)(?:.)(update)(?:\scfg_skill_level\sset\slevel_\s=\s)([\d])(?:\swhere\sperson_dbid\s=\s)(\d{4})(?:\sand\sskill_dbid\s=\s)(\d{4})" 'Set pattern.
regEx.IgnoreCase = True ' Set case insensitivity.
regEx.Global = False     ' Set global applicability.

Set Matches = regEx.Execute(strResult)    ' Execute regex search.

If Matches.Count > 0 Then
    For Each Match In Matches
        text1 = Match.SubMatches(0)
        text2 = Match.SubMatches(1)
        text3 = Match.SubMatches(2)
        text4 = Match.SubMatches(3)
        text5 = Match.SubMatches(4)
        text6 = Match.SubMatches(5)

        strTargetHr = Left(Match.SubMatches(1), 2)
        strTargetmin = Mid(Match.SubMatches(1), 4, 2)
        strTargetSec = Mid(Match.SubMatches(1), 7, 2)
        dtTargetTime = TimeSerial(Val(strTargetHr), Val(strTargetmin), Val(strTargetSec))
        If dtTargetTime < dtTimePlaceholder Then
            dtTargetDate = DateAdd("d", 1, dtDatePlaceholder)
        Else
            dtTargetDate = dtDatePlaceholder
        End If
        strTargetDate = Format(dtTargetDate, "mm/dd/yyyy")
        dtTimePlaceholder = dtTargetTime
        dtDatePlaceholder = dtTargetDate

        Selection.InsertAfter Chr(10) & strTargetDate & "," & text1 & "," & text2 & "," & text3 & "," & text4 & "," & text5 & "," & text6
    Next Match
End If

我已经尝试制作一个长的正则表达式,将3个表达式组合起来,这些表达式使用here,但不在宏中。

我从上面收到的样本输出:

07/23/2014,Joy,14:13:01.395,update,1,7151,4002

1 个答案:

答案 0 :(得分:0)

Regex101

注意我添加了捕获组名称,这使您可以更轻松地过滤哪种类型。

注意: 你是正则表达式看起来正确,请确保你正在逃避字符串。只需在@前面添加",如下所示。

@"(?<search1>(?:user:\s.)(\w*)(?:].*\n.*\n.*\n.*\.*\n\s*.*\n)(\d*:\d*:\d*\.\d*)(?:.)(update)(?:\scfg_skill_level\sset\slevel_\s=\s)([\d])(?:\swhere\sperson_dbid\s=\s)(\d{4})(?:\sand\sskill_dbid\s=\s)(\d{4}))|(?<search2>(?:user:\s\[)(\w*)(?:].*\n.*\n.*\n.*\.*\n\s*.*\n)(\d*:\d*:\d*\.\d*)(?:\s)(delete)(?:\sfrom\scfg_skill_level\s\where\sperson_dbid\s=\s)(\d*)(?:\sand\sskill_dbid\s=\s)(\d*))|(?<search3>((?:user:\s\[)(\w*)(?:].*\n.*\n.*\n.*\.*\n\s*.*\n.)(\d*:\d*:\d*\.\d*)(?:\s)(insert)(?:\sinto\scfg_skill_level\s\()(?:.*\)\s\n\w*\()(\d*)(?:,\s)(\d*)(?:,\s)(.)(?:,\s)(.)(?:,\s)(.)))"