Reputation: 1100
I have a string that I know will contain one entry from an array of strings. I'm looking for which array entry the string contains.
If I have the following variables:
$String = "This is my string"
$Array = "oh","my","goodness"
I can verify if any of the array entries exist in the string with:
$String -match $($Array -join "|")
But, this will only return true or false. I want to know which entry was matched.
-Contains seems to be going in the right direction, but that only verifies if an array contains a specific object, and I want to verify which of the array entries is contained within the string. I'm thinking something like a foreach loop would do the trick, but that seems like a fairly resource intensive workaround.
Any help is appreciated!
Upvotes: 0
Views: 812
Reputation: 59822
That's what the automatic variable $Matches
is for.
$String = "This is my string"
$Array = "oh","my","goodness"
if($String -match $($Array -join "|"))
{
$Matches
}
Returns:
PS />
Name Value
---- -----
0 my
This is another way you can see the matches:
# Adding "This" for the example
$String = "This is my string"
[regex]$Array = "oh","my","goodness","This" -join '|'
$Array.Matches($String)
Returns:
PS />
Groups Success Name Captures Index Length Value
------ ------- ---- -------- ----- ------ -----
{0} True 0 {0} 0 4 This
{0} True 0 {0} 8 2 my
Upvotes: 1