Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python - string match only whole words

Tags:

python

I have two lists - query and line. My code finds if a query such as:

["president" ,"publicly"]

Is contained in a line (order matters) such as:

["president" ,"publicly", "told"]

And this is the code I'm currently using:

if ' '.join(query) in ' '.join(line)

Problem is, I want to match whole words only. So the query below won't pass the condition statement:

["president" ,"pub"]

How can I do that?

like image 990
Tom Avatar asked Feb 28 '26 00:02

Tom


1 Answers

Here is one way:

re.search(r'\b' + re.escape(' '.join(query)) + r'\b', ' '.join(line)) is not None
like image 149
NPE Avatar answered Mar 01 '26 15:03

NPE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!