-
Notifications
You must be signed in to change notification settings - Fork 19
/
regex_file_search.py
64 lines (54 loc) · 2.25 KB
/
regex_file_search.py
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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#! python3
import re
import pprint
import argparse
import textwrap
from Typing import List
def find_match(file: str, pattern: str) => List[str]:
"""
searches through every line in a given file, and returns the lines that match the regex
file: str, location of the file to search through
pattern: str, regex to match to
out: List[str], a list containing all lines where regex matched
"""
out = []
ptrn = re.compile(pattern)
with open(file) as f:
for line in f.readlines():
if ptrn.search(line):
out.append(line.strip())
return out
if __name__ == "__main__":
re_eli5 = textwrap.dedent("""
-------------------
Building a pattern:
Any letter/number -> matches itself
^ -> matches start of the line
$ -> matches end of the line
. -> matches one of any character
\d -> matches any digit
\D -> mathes anything that is not a digit
\s -> matches any whitespace
( ) -> used to group things together
[ ] -> matches one of the items inside
+ -> matches one or more of the previous thing
* -> matches zero or more of the previous thing
? -> matches zero or one of the previous things
| -> matches either the left or the right thing
\ -> used to "escape" a special character and match it literally (one of the ".^$()[]+*?|" for example)
""")
parser = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter,
description=f"Find all lines in a file that mathch given criteria", epilog=re_eli5)
parser.add_argument("pattern", help=f"Regular Expression to match the text.")
parser.add_argument("file", help="File with the list of words to match.", metavar="in_file")
parser.add_argument("--out", "-o", help="Optional output file, will print on screen if not given", default=None,
metavar="out_file")
args = parser.parse_args()
result = find_match(args.file, args.pattern)
if args.out is not None:
with open(args.out, "w") as o:
for match in result:
print(match, file=o)
print("Done!")
else:
pprint.pprint(result)