python - Check if substring is in string -


let's have list

test = ["a","bb","ph","phi","phi_ph"] 

where member of test can either contain string ph, string phi, combination of these two, or none of them. how can filter list retain elements containing ph such that:

test_filtered = ["ph","phi_ph"] 

when e.g.

[x x in test if 'ph' in x] 

returns

>> ["ph","phi","phi_ph"] 

the solution using re.compile() , re.search() functions:

import re  test = ["a","bb","ph","phi","phi_ph", "phi_abc", "ph_a"] search_str = 'ph'  pattern = re.compile(r'(^|[^a-z0-9])'+ search_str + '([^a-z0-9]|$)') result = [i in test if re.search(pattern, i)]  print(result) 

the output:

['ph', 'phi_ph', 'ph_a'] 

(^|[^a-z0-9]) - alternation group, ensures search string(i.e. ph) should occur @ start of string or preceded non-alphanumeric character

([^a-z0-9]|$) - alternation group, ensures search string(i.e. ph) should occur @ end of string or followed non-alphanumeric character


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -