Best unofficial Apache Server developers community
Username
Forgot password?
Sign in with Twitter account
Sign in with Facebook account

Regex is causing an error that I can't seem to find.

0

50 views

The code below worked fine until I added the regex line. When I comment it out, the code works again ... I'm stumped. I'm only using a regex to search a file for three different type of strings concurrently(ascii, hex, string). Any help is appreciated, thanks!

 elif searchType =='2':
          print "  Directory to be searched: c:\Python27 "
          directory = os.path.join("c:\\","Python27")
          userstring = raw_input("Enter a string name to search: ")
          userStrHEX = userstring.encode('hex')
          userStrASCII = ' '.join(str(ord(char)) for char in userstring)
          regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) )
          for root,dirname, files in os.walk(directory):
             for file in files:
                 if file.endswith(".log") or file.endswith(".txt"):
                    f=open(os.path.join(root, file))
                    for line in f.readlines():
                       #if userstring in line:
                       if regex.search(line):       
                          print "file: " + os.path.join(root,file)           
                          break
                    else:
                       print "String NOT Found!"
                       break
                    f.close()

asked April 27, 2011 8:56 am CDT
posted via StackOverflow

1 Answer

2
Best answer
 

When I ran this code, I got an error like

File "search.py", line 7
    for root,dirname, files in os.walk(directory):
      ^
SyntaxError: invalid syntax

This is because the previous line, which contains the compiled regular expression, is missing a closing parentheses:

regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) )

should read

regex = re.compile( "(%s|%s|%s)" % ( re.escape( userstring ), re.escape( userStrHEX ), re.escape( userStrASCII ) ) )

answered April 27, 2011 9:23 am CDT

Your answer

Join with account you already have


Sign in with Twitter account
Sign in with Facebook account
Sign in with Google Friend Connect

Preview
Similar questions
Linux find regex
April 12, 2011