Alex Lord Alex Lord - 19 days ago 6
HTML Question

Python CGI/RE Help Needed

I understand most of the following code and what it does except for the

if re.search(str(searchString), line) != None:
line - which is near the bottom.

The code accepts a string input by the user on another HTML form and then this python script runs to check a file if the entered string/words is in that file and then prints all lines with the word in.

import cgi, re

print ('Content-type: text/html \n')
print ('<html>')
print ('<head>')
print ('<title>Web Client Server File Search Example </title>')
print ('</head>')
print ('<body>')
print ("<H1>Search Text Example </H1>")

form = cgi.FieldStorage()
searchString = form.getvalue('search')
print("<br><H2 style='color:red;'> Search String: ", searchString)
fh = open("animals.txt")
fhdatalist = fh.readlines()

for line in fhdatalist:
line = line.rstrip()
if re.search(str(searchString), line) != None:
print ('<br>Line Found: ', line)

fh.close()


Could someone briefly explain how it/the search() works please?

Answer
searchString = form.getvalue('search')   

this line takes the search value entered in a form on the HTML page

if re.search(str(searchString), line) != None:

this line takes each line in the animals.txt file and checks if the search word is found in that line. If it's found, that line from animals.txt is printed.

re is the python regular expression parser, which is extremely powerful and you should check it out!

Python2.7: https://docs.python.org/2/library/re.html

Python3.5: https://docs.python.org/3/library/re.html

======

And now, a word of warning. You are letting the viewer of your web page interact directly with your code. What if I searched for the following terms? Try it and see what happens:

.*
*
Comments