How to get the captured groups from Select-String?

前端 未结 5 806
清酒与你
清酒与你 2020-12-05 16:41

I\'m trying to extract text from a set of files on Windows using the Powershell (version 4):

PS > Select-String -AllMatches -Pattern 

        
5条回答
  •  生来不讨喜
    2020-12-05 17:29

    According to the powershell docs on Regular Expressions > Groups, Captures, and Substitutions:

    When using the -match operator, powershell will create an automatic variable named $Matches

    PS> "The last logged on user was CONTOSO\jsmith" -match "(.+was )(.+)"
    

    The value returned from this expression is just true|false, but PS will add the $Matches hashtable

    So if you output $Matches, you'll get all capture groups:

    PS> $Matches
    
    Name     Value
    ----     -----
    2        CONTOSO\jsmith
    1        The last logged on user was
    0        The last logged on user was CONTOSO\jsmith
    

    And you can access each capture group individually with dot notation like this:

    PS> "The last logged on user was CONTOSO\jsmith" -match "(.+was )(.+)"
    PS> $Matches.2
    CONTOSO\jsmith
    

    Additional Resources:

    • To Get Multiple Matches, see How to capture multiple regex matches
    • To Pass Options/Flags, see Pass regex options to PowerShell [regex] type

提交回复
热议问题