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
Why Is This Python Script With Matplotlib So Slow
Pandas | Merge Rows With Same Id
Send a File Through Sockets in Python
Python: Create 50 Objects Using a for Loop
Creating a List of Random Numbers Without Duplicates in Python
How to Assign Class Instance to a Variable and Use That in Other Class
Sharing a Complex Object Between Processes
How to Decompile a Compiled .Pyc File into a .Py File
How to Create Dynamic Workflows in Airflow
Pyspark Data Frame Converting False and True to 0 and 1
How to Make Tkinter Frames in a Loop and Update Object Values
How to Check for an Exact Word in a String in Python
Finding an Exact Substring in a String in Python
How to Display the Value of the Bar on Each Bar With Pyplot.Barh()
Get All the Diagonals in a Matrix/List of Lists in Python
Matrix Flip Horizontal or Vertical
Python Works in Pycharm But Not from Terminal
How to Write to an Existing Excel File Without Overwriting Data (Using Pandas)