简体   繁体   中英

regular expression to ckeck if multiple patterns exitst in list

l = ['abc_123','abc_456','ade_098','def_765','deg_432']

patterns=['a.*3','def.*']

I'm trying to come up with a regular expression that simultaneously checks if both patterns in patterns exist in list l . In the example above, this is true because ' abc_123 ' and ' def_765 ' match each of the patterns in patterns . I thought of

[s for s in l if ((re.match(patterns[0], s)) or (re.match(patterns[1], s)))]

but what should I do if I have a list like the following?

l = ['abc_123','abc_456','ade_093','deh_765','deg_432']

In this example, the code above will give me two results but only the pattern ' a.*3 ' is matched.

Ideally I would like to return True if both patterns are matched and False otherwise.

I can do something like

pat0 = [s for s in l if re.match(patterns[0], s)]
pat1 = [s for s in l if re.match(patterns[1], s)]

and check if both pat0 and pat1 are not empty, but this seems kind of wasteful, especially if my lists are long and there are several patterns.

You can try:

>>> patterns=['a.*3','def.*']
>>> 
>>> l1 = ['abc_123','abc_456','ade_098','def_765','deg_432']
>>> all((any(re.match(p,s) for s in l1) for p in patterns))
True # b/c 'a.*3' matches 'abc_123' AND 'def.*' matches def_765
>>>
>>> l2 = ['abc_123','abc_456','ade_093','deh_765','deg_432']
>>> all((any(re.match(p,s) for s in l2) for p in patterns))
False # b/c 'a.*3' matches 'abc_123' BUT there is not match for 'def.*' 

This is very basic boolean logic. You are using or . That returns true if either are true. You need and , which only returns true if both are ture, or if both conditions are matched in your case.

Your final code would be [s for s in l if ((re.match(patterns[0], s)) and (re.match(patterns[1], s))]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM