I am studying PowerShell. I want to know how to check if a string contains any substring in an array in PowerShell. I know how to do the same in Python. The code is given below:
any(substring in string for substring in substring_list)
Is there similar code available in PowerShell?
My PowerShell code is given below.
$a = @('one', 'two', 'three') $s = "one is first"
I want to validate $s with $a. If any string in $a is present in $s then return True. Is it possible in PowerShell?
If you want to know in PowerShell if a string contains a particular string or word then you will need to use the -like operator or the . contains() function. The contains operator can only be used on objects or arrays just like its syntactic counterpart -in and -notin .
Check Elements of an Array of String in PowerShellThe “Contains()” method is utilized for checking if a particular string exists as an array element. To utilize this method, specify the string value as a parameter in the “Contains()” function. “$str” array contains “JAVA” but not “CB” as elements.
You can use contains(), indexOf() and lastIndexOf() method to check if one String contains another String in Java or not. If a String contains another String then it's known as a substring. The indexOf() method accepts a String and returns the starting position of the string if it exists, otherwise, it will return -1.
Using the actual variables in the question for simplicity:
$a = @('one', 'two', 'three') $s = "one is first" $null -ne ($a | ? { $s -match $_ }) # Returns $true
Modifying $s to not include anything in $a:
$s = "something else entirely" $null -ne ($a | ? { $s -match $_ }) # Returns $false
(That's about 25% fewer characters than chingNotCHing's answer, using the same variable names of course :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With