0

I have two text files that I have turned into lists. List1 has lines that look like this:

'U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah'

list2 has lines that look like this:

['smuspid\n', 'USAA032367605\n', 'USAA032367776\n', 'USAA044754265\n', 'USAA044754267\n']

I want to return every line in list1 that has a match in list2. I've tried using regex for this:

found = []
check = re.compile('|'.join(list2))
for elem in list1:
    if check.match(elem):
        found.append(elem)

but my code above is returning an empty list. Any suggestions?

1
  • you want match or exact equal Commented Nov 9, 2019 at 0:06

1 Answer 1

2

I guess you can do that without a regular expression:

Method 1

list1 = ['U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah']

list2 = ['|USAA032812134', '|USAA0328121304', '|USAA032999812134']

found = []
for i in list1:
    for j in list2:
        if j in i:
            found.append(j)

print(found)

Output 1

['|USAA032812134']

Method 2 using List Comprehension

list1 = ['U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah']
list2 = ['|USAA032812134', '|USAA0328121304', '|USAA032999812134', 'blah']

print([j for i in list1 for j in list2 if j in i])

Output 2

['|USAA032812134', 'blah']

Method 3: strip() for new lines

You can simply strip() and append() to your found list:

list1 = ['U|blah|USAA032812134||blah|blah|25|USAA032812134|blah|A||4||blah|2019-05-28 12:54:59|blah|123456||blah']
list2 = ['smuspid\n', 'USAA032812134\n', 'USAA032367605\n', 'USAA032367776\n',
         'USAA044754265\n', 'USAA044754267\n']

found = []
for i in list1:
    for j in list2:
        if j.strip() in i:
            found.append(j.strip())

print(found)

Output 3

['USAA032812134']
Sign up to request clarification or add additional context in comments.

1 Comment

Sorry, list2 has a different format than what I previously thought, I edited the question to show what the elements look like. Does that change your code because this method still returned an empty list when I tried it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.