问题
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 capturing both to the Powershell magic variable $matches?
If I run the following code in Powershell:
$string = "blah blah F12 blah blah F32 blah blah blah"
$string -match "F\d\d"
The $matches variable only contains F12
I also tried:
$string -match "(F\d\d)"
This time $matches had two items, but both are F12
I would like $matches to contain both F12 and F32 for further processing. I just can't seem to find a way to do it.
All help would be greatly appreciated. :)
回答1:
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."
回答2:
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
回答3:
$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
来源:https://stackoverflow.com/questions/3141851/how-to-capture-multiple-regex-matches-from-a-single-line-into-the-matches-mag