python re.search不适用于多行字符串 [英] python re.search not working on multiline string

查看:235
本文介绍了python re.search不适用于多行字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已将此文件加载为字符串:

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
    };

我只想获取带有1和0的块,然后以某种方式对其进行处理.

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

我导入了re,并尝试过:

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]: []

为什么不匹配任何东西?如何解决这个问题? (是python3)

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

推荐答案

您需要使用re.S标志,而不是re.M.

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

  • re.M(re.MULTILINE)控制^$的行为(无论它们在整个字符串的开头/结尾还是在每行的开头都匹配).
  • re.S(re.DOTALL)控制.的行为,并且是您要允许点与换行符匹配时需要的选项.
  • 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.

另请参见文档.

这篇关于python re.search不适用于多行字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆