1
我正在編寫一個程序來使用Python RegEx通過日誌消息進行解析。我已經掌握了一切,直到日誌的消息。這可以是任意數量的字符類型,所以我假設。*通配符將是解決此問題的最佳解決方案。它匹配除了新行之外的所有內容。爲什麼Python正則表達式通配符只匹配newLine
但是,當我使用通配符時,唯一返回的是此實例中的新行。有任何想法嗎?下面的代碼和輸出:
import os
import re
#Change to and print correct file path
os.chdir('/Users/MacUser/Desktop/regExPython')
print(os.getcwd())
#Iterate and read from syslogexample.txt then print results
line_number = 0
with open('syslogexample.txt', 'r') as syslog:
log_lines = syslog.readlines()
for line in log_lines:
line_number += 1
print('{:>4} {}'.format(line_number, line.rstrip()))
#Build regex to parse through the data
DATE_RE = r'(\w{3}\s+\d{2})'
TIME_RE = r'(\d{2}:\d{2}:\d{2})'
DEVICE_RE = r'(\S+)'
PROCESS_RE = r'(\S+\s+\S+:)'
MESSAGE_RE = r'(.*)'
CD_RE = r'(\s+)'
Syslog_RE = DATE_RE + CD_RE + \
TIME_RE + CD_RE + \
DEVICE_RE + CD_RE + \
PROCESS_RE + CD_RE + \
MESSAGE_RE
#Use regex to parse through the data
for line in log_lines:
m = re.match(Syslog_RE, line)
if m:
print(m.groups())
#Printed log Files
1 apr 29 08:22:13 mac-users-macbook-8 syslogd[49]: asl sender statistics
2 apr 29 08:22:17 mac-users-macbook-8 com.apple.xpc.launchd[1] (com.apple.xpc.launchd.domain.system):
3 service "com.apple.emond.aslmanager" tried to hijack endpoint "com.apple.aslmanager" from owner:
4 com.apple.aslmanager
5 apr 29 08:22:17 mac-users-macbook-8 com.apple.xpc.launchd[1] (com.apple.xpc.launchd.domain.system):
6 service "com.apple.emond.aslmanager" tried to hijack endpoint
7 "com.apple.activity_tracing.cache-delete" from owner: com.apple.aslmanager
8 apr 29 08:22:17 mac-users-macbook-8 com.apple.xpc.launchd[1] (com.apple.bsd.dirhelper[14184]):
9 endpoint has been activated through legacy launch(3) apis. please switch to xpc or
10 bootstrap_check_in(): com.apple.bsd.dirhelper
11 apr 29 08:22:19 mac-users-macbook-8 com.apple.xpc.launchd[1]
12 (com.apple.imfoundation.imremoteurlconnectionagent): unknown key for integer:
13 _dirtyjetsammemorylimit
Parsed Log Files
('apr 29', ' ', '08:22:17', ' ', 'mac-users-macbook-8', ' ', 'com.apple.xpc.launchd[1] (com.apple.xpc.launchd.domain.system):', '\n', '')
('apr 29', ' ', '08:22:17', ' ', 'mac-users-macbook-8', ' ', 'com.apple.xpc.launchd[1] (com.apple.xpc.launchd.domain.system):', '\n', '')
('apr 29', ' ', '08:22:17', ' ', 'mac-users-macbook-8', ' ', 'com.apple.xpc.launchd[1] (com.apple.bsd.dirhelper[14184]):', '\n', '')
Process finished with exit code 0
正如你可以在年底看到MESSAGE_RE是唯一打印的字符不,我認爲不會在所有打印\ n換行字符。
謝謝大家!
的'「\ n''s是CD_RE比賽,MESSAGE_RE總是產生'」'',因爲沒有什麼留在管道。由於您一次只查看一行代碼,並且這些消息始終位於不同的行中,因此MESSAGE_RE不可能匹配任何內容。 – jasonharper
問題是每個日誌都可以被分割成任意數量的文本行。這很奇怪,因爲在我認識的每個日誌系統中(包括Apple),每行總是有一條消息。如果你能以原始形式獲得日誌,那就是最乾淨的解決方案。 如果您絕對需要使用正則表達式進行多行匹配,請查看['re.S'](https://docs.python.org/2/library/re.html#re.S) – pietrodn