Get matches from Powershell string

I want to collect regex matches on 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

returns the entire string, but I want for to $myMatches

return like 2014-89463

(and the rest of any matches, there will be more).

Also, it $myString

is an array of strings, each of which matches the one above.

Thanks for any help!

+3


source to share


1 answer


Try the following:

[regex]::Matches([string]$mystring,'(\d{4}-\d{5})') |
foreach {$_.groups[1].value}

      



Dropping $mystring

in [string]

makes it one long line with space separating each element. The static method then [regex]::Matches()

returns all matches found in the string. The returned match objects will have a Group object for each captured group, and the property will have a .value

captured value. The loop foreach

just repeats on all matches and splashes out the value of capture group 1.

+2


source







All Articles