How to Check for an Exact Word in a String in Python

Finding an exact word in list

in means contained in, 'abc' in 'abcd' is True. For exact match use ==

matching = [x for x in lines if keyword.lower() == x.lower()]

You might need to remove spaces\new lines as well

matching = [x for x in lines if keyword.lower().strip() == x.lower().strip()]

Edit:

To find a line containing the keyword you can use loops

matches = []
for line in lines:
for string in line.split(' '):
if string.lower().strip() == keyword.lower().strip():
matches.append(line)

How to find an exact word in a string in python

You may consider the following approaches.

TLS as a whole word should have a word boundary right in front of it, so that part is covered in your pattern.

If there must be a whitespace right after 1, or end of string, it is more efficient to use a negative lookahead (?!\S): r'\bTLS 1(?!\S)'. Well, you may also use r'\bTLS 1(?:\s|$)'. See this regex demo.

If you just want to ensure there is no digit or a fractional part after 1 use

r'\bTLS 1(?!\.?\d)'

This will match TLS 1 that has no . or . + digit after it. See this regex demo.

Python demo:

import re
target = ['TLS 1.2 x67 DHE-RSA-AES128-SHA256 DH 2048 AES128 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256', 'TLS 1 x67 DHE-RSA-AES128-SHA256 DH 2048 AES128 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256',
'TLS 1.1 x67 DHE-RSA-AES128-SHA256 DH 2048 AES128 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256']
lines=[]
for i in target:
if re.match(r'\bTLS 1(?!\.?\d)', i):
lines.append(i)
print(lines)

Output:

['TLS 1 x67 DHE-RSA-AES128-SHA256 DH 2048 AES128 TLS_DHE_RSA_WITH_AES_128_CBC_SHA256']

Check if a word is in a string in Python

What is wrong with:

if word in mystring: 
print('success')


Related Topics



Leave a reply



Submit