Steven G
Steven G

Reputation: 17122

using REGEX to 2 combination of letter in a list of strings python

I am trying to extract the string that contain 2 set of 3 characters such has:

x = ['USDGBP.q', 'CADUSD.q', 'GBPCAD.q']

I am trying to extract the string that contains USD & GBP. but the USD and GBP coud be GBPUSD or USDGBP

so in the example, it would return

'USDGBP.q'

any way to achieve this through regex?

Upvotes: 2

Views: 50

Answers (2)

ospahiu
ospahiu

Reputation: 3525

You can emulate Logical AND with regex using positive look-aheads. This strictly matches GBPUSD or USDGBP.

>>> import re
>>> pattern = re.compile(r'(?=.*USD)(?=.*GBP)')
>>> x = ['USDGBP.q', 'CADUSD.q', 'GBPCAD.q', 'GBPUSD.q']
>>> print filter(lambda item: re.findall(pattern, item), x)
['USDGBP.q', 'GBPUSD.q']

But if you needed a more lenient regex to match any string containing both tokens:

r'.*(?=.*USD).*(?=.*GBP).*')

Upvotes: 1

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

You can use a list comprehension:

x = ['USDGBP.q', 'CADUSD.q', 'GBPCAD.q']
print([s for s in x if 'USD' in s and 'GBP' in s])

See the Python demo.

It will return the items from x that contain both USD and GBP.

Upvotes: 1

Related Questions