Search code examples
pythonfilematchpython-re

re.match function doesn't detect line in file


I wanted to detect in which line, the section '' is. I used python to it. I used re.match(), but it does not detect that obvious line:

import re
filereader = open("template.html", "r") 
template = filereader.readlines()
filereader.close()
for d in range(len(template)):
    if re.match(r'.*<body onload="init(0,0);">.*',template[d]):
        wherebody = d
        break
print(wherebody)

Where is the error? Note: HTML file HAS the


Solution

  • As you can see in this example: https://regex101.com/r/6JcYhk/1, your regex does not work in matching text with <body onload="init(0,0);">. This is because ( and ) are interpreted as the Regex group start and end tokens. You can resolve this by escaping these characters, which matches the literal ( and ) instead:

    ...
        if re.match(r'.*<body onload="init\(0,0\);">.*',template[d]):
    ...
    

    (You can try this out in the aforementioned example, and you'll see that it starts to match)