开发者

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

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 开发者_StackOverflow中文版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()


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 ) ) )
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜