Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python re.search not working on multiline string

I have this file loaded in string:

// some preceding stuff
static char header_data[] = {
    1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1,
    1,1,1,0,1,1,0,1,1,0,1,1,0,1,1,1,
    1,1,0,1,0,1,0,1,1,0,1,0,1,0,1,1,
    1,0,1,1,1,0,0,1,1,0,0,1,1,1,0,1,
    0,0,0,1,1,1,1,1,1,1,1,1,1,0,1,1,
    1,0,0,0,1,1,0,1,1,1,1,1,0,1,1,1,
    0,1,0,0,0,1,0,0,1,1,1,1,0,0,0,0,
    0,1,1,0,0,0,0,0,0,1,1,1,1,1,1,0,
    0,1,1,1,0,0,0,0,0,0,1,1,0,1,1,0,
    0,0,0,0,1,0,0,0,1,0,0,1,0,1,0,0,
    1,1,1,0,1,1,0,0,1,1,0,0,0,1,1,1,
    1,1,0,1,1,1,1,1,1,1,1,0,0,0,1,1,
    1,0,1,1,1,0,0,1,1,0,0,0,0,0,1,1,
    1,1,0,1,0,1,0,1,1,1,1,0,0,0,0,1,
    1,1,1,0,1,1,0,1,1,0,1,1,1,1,0,1,
    1,1,1,1,1,1,0,0,0,0,1,1,1,1,1,1
    };

I want to get only the block with ones and zeros, and then somehow process it.

I imported re, and tried:

In [11]: re.search('static char header_data(.*);', src, flags=re.M)

In [12]: re.findall('static char header_data(.*);', src, flags=re.M)
Out[12]: []

Why doesn't it match anything? How to fix this? (It's python3)

like image 221
MightyPork Avatar asked Oct 31 '25 08:10

MightyPork


1 Answers

You need to use the re.S flag, not re.M.

  • re.M (re.MULTILINE) controls the behavior of ^ and $ (whether they match at the start/end of the entire string or of each line).
  • re.S (re.DOTALL) controls the behavior of the . and is the option you need when you want to allow the dot to match newlines.

See also the documentation.

like image 161
Tim Pietzcker Avatar answered Nov 02 '25 23:11

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!