0

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!

1 Answer 1

1

That's what the automatic variable $Matches is for.

See about_Regular_Expressions

$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
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.