2

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.

1
  • 1
    Can you please add your attempt (using the foreach loop) ? Commented Jan 20, 2023 at 18:06

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

2

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


Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.