Home > Enterprise >  re.match function doesn't detect line in file
re.match function doesn't detect line in file

Time:01-19

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 onl oad="init(0,0);">.*',template[d]):
        wherebody = d
        break
print(wherebody)

Where is the error? Note: HTML file HAS the

CodePudding user response:

As you can see in this example: https://regex101.com/r/6JcYhk/1, your regex does not work in matching text with <body onl oad="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 onl oad="init\(0,0\);">.*',template[d]):
...

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

  •  Tags:  
  • Related