I wish to know if a string contains one of abc
, def
, xyz
, etc. I could do it like:
$a.Contains("abc") -or $a.Contains("def") -or $a.Contains("xyz")
Well it works, but I have to change code if this substring list changes, and the performance is poor because $a
is scanned multiple times.
Is there a more efficient way to do this with just one function call?
You can use any : a_string = "A string is more than its parts!" matches = ["more", "wholesome", "milk"] if any(x in a_string for x in matches): Similarly to check if all the strings from the list are found, use all instead of any . any() takes an iterable.
The easiest way to check if a Python string contains a substring is to use the in operator. The in operator is used to check data structures for membership in Python. It returns a Boolean (either True or False ).
1 Basic Syntax The basic syntax is pretty easy. You use the match keyword and the case keyword and can then match a variable against different values. For each matched case you can then perform a certain action.
Using “contains” to Find a Substring in a Pandas DataFrame The contains method returns boolean values for the Series with True for if the original Series value contains the substring and False if not. A basic application of contains should look like Series. str. contains("substring") .
You could use the -match method and create the regex automatically using string.join:
$referenz = @('abc', 'def', 'xyz')
$referenzRegex = [string]::Join('|', $referenz) # create the regex
Usage:
"any string containing abc" -match $referenzRegex # true
"any non matching string" -match $referenzRegex #false
Regex it: $a -match /\a|def|xyz|abc/g (https://regex101.com/r/xV6aS5/1)
source: http://ss64.com/ps/syntax-regex.html
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