2011-04-27 31 views
1

在下面的代碼,我搜索字符串,十六進制和ASCII ....如果字符串匹配,該文件,其中字符串被匹配被打印。有沒有辦法打印什麼字符串類型匹配(十六進制,ASCII碼或字符串)?另外,我想考慮大寫和小寫,以及數字[0-9] +。我不知道我是否可以將它添加到相同的正則表達式,或者倒不如增加另一個正則表達式行:我可以打印什麼字符串格式是從多個字符串匹配,正則表達式搜索

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

回答

2
result = regex.search(line) 
print result.group() 

的regex.search將返回一個結果對象。 result.group()返回的是匹配字符串的列表,在您的情況下,它將包含1個項目的列表,匹配字符串HEX,ASCII或字符串。

+0

朱利安 - 當你說要組()的調用,你是什麼意思?我還是難倒這個 – suffa 2011-04-29 12:43:06

+0

'結果= regex.search(線)'' 打印result.group()' – 2011-04-29 12:49:24

4

這個怎麼樣?

for line in f.readlines(): 
    if userstring in line: 
     print 'User input in file: ' + os.path.join(root, file) 
     break 
    elif userStrHEX in line: 
     print 'HEX string in file: ' + os.path.join(root, file) 
     break 
    elif userStrASCII in line: 
     print 'ASCII string in file: ' + os.path.join(root, file) 
     break 

看你的正則表達式(三種可能的話,並沒有真正的正則表達式的功能之一),我會避免使用正則表達式的。

您可以輕鬆地添加更多的功能:

elif userstring.lower() in line.lower(): 
     print 'User input (case-insensitive) in file: ' + os.path.join(root, file) 
     break 

只是檢查你的條件,爲了能趕上合適的情況下(即,如果你之前區分大小寫檢查大小寫不敏感,後者將永遠不會發生,等。)

+0

謝謝!但爲了知道,我如何在上面的正則表達式中添加一個不區分大小寫的功能(例如re.IGNORECASE)? – suffa 2011-04-27 16:00:13

相關問題