How to search for regular expressions when reading a file in python

When reading a text file in python we are reading the file using readlines() method which reads the file line-by-line.

fn = open(/path/to/myfile, 'r')

The first approach is to search for regular expression in single lines as follows. The \{(.*?)\} regex matches everything within curly brackets.

for currline in fnlines:
    match_regex = re.match('\{(.*?)\}', currline)
    if match_regex:

The second approach is to concatenate the file in a single line string.

s = ""
for i in fnlines:
    s += str(i)
    running = True
    while running:
        r ='\{(.*?)\}', s)
        if r:
            running = False

Check python documentation on regex, except re.match and see also re.findall and the flags (IGNORECASE etc).

Latest posts