Reputation:
I want to collect the matches to a regex in a specific string, and put them into an array.
This is a simplification of my code so far.
$myString = <p>a bunch of html</p> <a href="example.com/number1?ID=2014-89463">go</a>
$myMatches = $myString -match "\d{4}-\d{5}"
Write-Host $myMatches
$myMatches
is returning the whole string, but what I want, is for $myMatches
to return as 2014-89463
(and the rest of any matches, be there more).
Also, $myString
is actually an array of strings, each similar to the one listed above.
Thanks for any help!
Upvotes: 3
Views: 1703
Reputation: 68273
Try this:
[regex]::Matches([string]$mystring,'(\d{4}-\d{5})') |
foreach {$_.groups[1].value}
Casting $mystring
to [string]
makes it all one long string, with a space separating each element. Then the [regex]::Matches()
static method returns all of the matches found in the string. The match objects returned will have a Group object for each captured group, with the .value
property being the captured value. The foreach
loop just iterates through all the matches, and spits out the value of capture group 1.
Upvotes: 2