Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a string contains any substring in an array in PowerShell

Tags:

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?

like image 884
mystack Avatar asked Jul 24 '15 05:07

mystack


People also ask

How do you check if a string contains a substring 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 .

How do you check if a string is in an array PowerShell?

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.

How do you check if a string contains a certain substring?

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.


1 Answers

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 :-)

like image 141
Michael Sorens Avatar answered Sep 22 '22 07:09

Michael Sorens