PowerShell -match operator and multiple groups

前端 未结 5 1650
南笙
南笙 2021-02-20 01:28

I have the following log entry that I am processing in PowerShell I\'m trying to extract all the activity names and durations using the -match operator but I am onl

相关标签:
5条回答
  • 2021-02-20 01:48

    http://www.johndcook.com/regex.html gives a decent example

    And, by all means, simplify your expression:

    ^([^-]+)\s*-\s*duration\(([0-9]+)
    
    • start at the beginning of the line
    • capture all characters leading up to the first -
    • make sure there's a -
    • skip whitespace
    • make sure the word "duration(" exists
    • capture all digits after "duration("
    0 讨论(0)
  • 2021-02-20 01:49

    The -match operator is meant to be used just once; it doesn't do a global match on the input. Keith Hill put a suggestion for a -matchall operator on Microsoft connect here.

    I'll suggest another way to do it. If the log entry is in a file, you can use the switch statement to accomplish the same thing:

    switch -regex -file .\log.txt { $entryRegex { $matches[1] + ", " + $matches[2] } }
    

    This is the output I get with this statement if $entryRegex has the regular expression you defined:

    Get Client Model, 0
    Parse Expression, 0
    Get Abstract Query, 0
    Compile Query, 0
    Execute Query, 63695
    Get Query Plan Complexity, 0
    Total, 63696
    Async Total, 63696
    
    0 讨论(0)
  • 2021-02-20 01:52

    You can include Regular Expression Options in an expression, but sadly, Global does not appear to be one of the available options.

    0 讨论(0)
  • 2021-02-20 01:58

    You can do this with the Select-String cmdlet in V2 but you need to specify the -AllMatches switch e.g.:

    $formattedMessage | Select-String 'regexpattern' -AllMatches
    

    Keep in mind that with the -match operator the primary thing you are doing is looking for "a" match i.e. is the regex pattern matched or not.

    0 讨论(0)
  • 2021-02-20 02:05

    I was able to get all of the groups by defining a Regex and then calling .Matches on that Regex. Still curious to know if this can be done with the -match operator in PowerShell.

    $detailRegex = [regex]"(Get\sClient\sModel|Parse\sExpression|Get\sAbstract\sQuery|Compile\sQuery|Execute\sQuery|Get\sQuery\sPlan\sComplexity|Async\sTotal|Total)\s-\sduration\(([0-9]*)"
    $detailRegex.Matches($formattedMessage)
    
    0 讨论(0)
提交回复
热议问题