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')
fnlines=fn.readlines()
fn.close()

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:
        print(match_regex.group())

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 = re.search('\{(.*?)\}', s)
        if r:
            print(r.group())
        else:
            running = False

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

Latest posts