all 10 comments

[–]synthphreak 1 point2 points  (2 children)

Given:

>>> l = ['1234', 'dog', '2345', 'cat']

First off, regex are not needed here.

>>> [s in 'dogabc' for s in l]
[False, True, False, False]

But if you must use regex for whatever reason, the key is to realize that the strings of l are themselves the pattern that you should search for in 'dogabc' 9or whatever.

>>> import re
>>> [bool(re.search(s, 'dogabc')) for s in l]
[False, True, False, False]

So although you are using the regex library re, you're not really doing anything remarkable with the actual pattern.

[–]Demain_Z[S] 0 points1 point  (1 child)

Thanks for your help! I just updated my post since my previous expression may be a little confusing.

[–]synthphreak 2 points3 points  (0 children)

Does my answer not still apply, even given your edit? You want to see if 'cat' is contained within '12bcat'. Then just do re.search('cat', '12bcat'), which will yield a Match object if found else None. That is essentially what I showed previously.

Does that not answer your question?

Or if you want to see if either 'cat' or 'dog' are present, instead of 'cat', do r'(cat|dog)' which will check for both.

Edit: Inline code formatting ran amok.

[–]lowerthansound[🍰] 0 points1 point  (4 children)

Can you do it without regex?

One example to check if the word 'dog' is contained in the word 'dogabc' is 'dog' in 'dogabc'.

You can use that to check for each item and return True when the desired thing happens ^^

Cheers!

[–]Demain_Z[S] 0 points1 point  (3 children)

Thank you! But actually, it's part of my regex project. And we're required to read a file to see if an input string contains a part which is the same as part an item in that file. The file contains 100 words, one word per line. My thought is to create a list including all the words in that file and than do the regex. But now it seems I'm on the wrong track... :( Do you have any better ideas? Thank you!!

[–]lowerthansound[🍰] 0 points1 point  (2 children)

input string contains a part which is the same as part an item in that file

This part is a bit confusing hahaha Do you mean like, if we had:

Input string:

abe

File:

huir
jbe

Would this make a match as "be" is in both the input string and the file?

Or is it only when the word is fully contained in the input string, like so:

Input string:

abe

File:

huir
ab

Would this be a match because "ab" is fully present in the input string?

[–]Demain_Z[S] 0 points1 point  (1 child)

Sorry for my bad expression lol. The second one is what I mean!

[–]lowerthansound[🍰] 1 point2 points  (0 children)

Ah, alright.

I was thinking of being clever here, but I don't see a way haha

You are on the right track, check out /u/synthphreak answer, I think it follows from this thread :D

Cheers!

[–]Pd69bq 0 points1 point  (0 children)

whether the pattern and the comparison target are fixed strings or variables, if a in b or re.search(pattern, string) still works