I'm trying to convert a perl regex to python equivalent.
Line in perl:
($Cur) = $Line =~ m/\s*\<stat\>(.+)\<\/stat\>\s*$/i;
What I've attempted, but doesn't seem to work:
m = re.search('<stat>(.*?)</stat>/i', line)
cur = m.group(0)
almost /i
means case insensitive
m = re.search(r'<stat>(.*?)</stat>',line,re.IGNORECASE)
also use the r
modifier on the string so you dont need to escape stuff like angle brackets.
but my guess is a better solution is to use an html/xml parser like beautifulsoup or other similar packages
Something like the following ...
r
is Python's raw string notation for regex patterns and to avoid escaping, after the prefix comes your regular expression following your string data. re.I
is used for case-insensitive matching.
See the re
documentation explaining this in more detail.
To find your match, you could use the group()
method of MatchObject like the following:
cur = re.search(r'<stat>([^<]*)</stat>', line).group(1)
Using search()
matches only the first occurrence, use findall()
to match all occurrences.
matches = re.findall(r'<stat>([^<]*)</stat>', line)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.