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

Time:01-21

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.

CodePudding user response:

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

CodePudding user response:

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)

CodePudding user response:

I would use regex and three "or" patterns.

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

True

Or select-string takes an array of patterns:

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

iit.apple


  • Related