How to capture multiple regex matches, from a single line, into the $matches magic variable in Powershell?

前端 未结 3 1700
遇见更好的自我
遇见更好的自我 2020-12-08 15:16

Let\'s say I have the string \"blah blah F12 blah blah F32 blah blah blah\" and I want to match the F12 and F32, how would I go about capt

相关标签:
3条回答
  • You can do this using Select-String in PowerShell 2.0 like so:

    Select-String F\d\d -input $string -AllMatches | Foreach {$_.matches}
    

    A while back I had asked for a -matchall operator on MS Connect and this suggestion was closed as fixed with this comment:

    "This is fixed with -allmatches parameter for select-string."

    0 讨论(0)
  • 2020-12-08 15:49
    $String = @'
    MemberProgram PackageID="12345678" ProgramName="Install"/
    MemberProgram PackageID="87654321" ProgramName="Install"/
    MemberProgram PackageID="21436587" ProgramName="Install"/
    MemberProgram PackageID="78563412" ProgramName="Install"/
    '@
    ([regex]'(?<=PackageID=\")\d+(?=\")').Matches($String).value
    
    0 讨论(0)
  • 2020-12-08 15:56

    I suggest using this syntax as makes it easier to handle your array of matches:

    $string = "blah blah F12 blah blah F32 blah blah blah" ;
    $matches = ([regex]'F\d\d').Matches($string);
    $matches[1].Value; # get matching value for second occurance, F32
    
    0 讨论(0)
提交回复
热议问题