Naveen Kumar
Naveen Kumar

Reputation: 1432

How to check whether array element matches with string using PowerShell?

Hi I want to check whether an string exist or start in set of array.

Example:

$str = "iit.apple"
$arr = ("apple", "mango", "grapes")

I want to check whether an array (arr) element matches or exist or starts with in string

I have tried using foreach loop to read each element but when matches found I am trying to break the loop.

Upvotes: 2

Views: 205

Answers (3)

js2010
js2010

Reputation: 27606

I would use regex and three "or" patterns.

'iit.apple' -match 'apple|mango|grapes'

True

Or

$str -match ($arr -join '|')

True

Or select-string takes an array of patterns:

$arr = "apple", "mango", "grapes"
$str | select-string $arr

iit.apple


Upvotes: 2

Santiago Squarzon
Santiago Squarzon

Reputation: 61293

To complement Mathias's answer here is how you do it with a foreach loop:

$str = "iit.apple"
$arr = "apple", "mango", "grapes"

$result = foreach($element in $arr) {
    if($str -like "*$element*") {
        $true
        break
    }
}
[bool] $result

Enumerable.Any can work too:

$delegate = [System.Func[object, bool]] {
    $str -like "*$($args[0])*"
}
[System.Linq.Enumerable]::Any($arr, $delegate)

Upvotes: 1

Mathias R. Jessen
Mathias R. Jessen

Reputation: 175085

Use the intrinsic .Where() method in First mode:

$str = "iit.apple"
$arr = ("apple", "mango", "grapes")

$anyMatches = $arr.Where({$str -like "*$_*"}, 'First').Count -gt 0

If any of the strings in $arr is a substring of $str, the Where(..) method will return a collection consisting of just that one element - so Where(...).Count -gt 0 will evaluate to $true

Upvotes: 4

Related Questions