简体   繁体   中英

Why doesn't this regular expression work on python

I am trying to extract some string from a binary file. When I use this regular expression with strings in linux it works fine but it does not work in python.

In strings :

strings -n 3 mke2fs | grep -E '^([0-9][0-9]*(\.[0-9]+)+)'

the result: 1.41.11

In python :

import re

f = open("mke2fs","rb").read()
for c in re.finditer('^([0-9][0-9]*(\.[0-9]+)+)',f):
 print c.group(1)

The result is empty. How can I resolve this? Is it because of my Python version (I'm using Python 2.7)? I tried using regex (another re alternative) still with no result.

You need the re.MULTILINE flag for ^ to work on your text like grep do.

BTW, it is more readable to use \\d :

for c in re.finditer(r'^(\d+(\.\d+)+)', f, re.MULTILINE):
    print c.group(1)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM