-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy path20_regularExpressionExample.py
More file actions
executable file
·35 lines (26 loc) · 1.26 KB
/
20_regularExpressionExample.py
File metadata and controls
executable file
·35 lines (26 loc) · 1.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#!/usr/bin/env python3
"""
Example using the regular expression library
https://docs.python.org/3/library/re.html
https://docs.python.org/3/library/os.html
Tools:
Evaluate regex online: https://regex101.com/
Another webpage with lots of examples: http://www.regexr.com/
Visual regex: https://www.debuggex.com/
Jens Dede, 2019, jd@comnets.uni-bremen.de
"""
import os
import re
# Join the paths in an OS independent way (/ vs \)
logfile = os.path.join("files", "logfileA.log") # Works for Windows and Linux
# Just check the timestamp, everything else does not matter
checkTerm1 = re.compile("^At timestamp (?P<timestamp>[.?\d]+)")
# Check the complete string
checkTerm2 = re.compile("^At timestamp (?P<timestamp>[.?\d]+) we received data: valueA=(?P<valueA>\-?[.?\d]+) valueB=(?P<valueB>\-?[.?\d]+)$")
with open(logfile, "r") as f: # Open file
for line in f: # Iterate over all lines
p = checkTerm2.match(line) # Check if the current lines matches the expression in checkTerm
if p: # If yes: Print it
print(p.group("timestamp"), p.group("valueA"), p.group("valueB"))
else:
print(5*"#", line[:-1]) # Otherwise print the raw line (and ignore the newline at the end)