Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test if a string contains one of multiple substrings?

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?

like image 569
vik santata Avatar asked Jun 30 '15 08:06

vik santata


People also ask

How do I check if a string contains multiple values in Python?

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.

How do you check if a list of substrings is in a string Python?

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

How do you match multiple values in Python?

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.

How do I check if a string contains a substring in pandas?

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") .


2 Answers

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
like image 125
Martin Brandl Avatar answered Sep 17 '22 13:09

Martin Brandl


Regex it: $a -match /\a|def|xyz|abc/g (https://regex101.com/r/xV6aS5/1)

  • Match exact characters anywhere in the original string: 'Ziggy stardust' -match 'iggy'

source: http://ss64.com/ps/syntax-regex.html

like image 26
d0n Avatar answered Sep 18 '22 13:09

d0n