Python regex does not match line start

不羁岁月 提交于 2021-02-02 09:28:51

问题


I have a text file with some data:

... 
DATA_ARRAY Some[] =
{
...
};

and I have a python 2.7 regex like this:

regx = re.compile("^DATA_ARRAY Some\[\].*?};", re.DOTALL)
regmatch = re.search(regx, data)
print regmatch.group(0)

The problem is that the regex does not match anything (regmatch is None). If I remove the ^ then it matches just fine.

What am I doing incorrectly here? I would like to add the line beginning search symbol.


回答1:


^ checks for start of the string.. add re.MULTILINE flag.

regx = re.compile("^DATA_ARRAY Some\[\].*?};", re.MULTILINE|re.DOTALL)



回答2:


The modifier ^ forces your regex engine to match the regex from start of string. and since your string doesn't start with DATA_ARRAY it returns None.

And as @nanny mentioned If you also want it to match the start of each line, use re.MULTILINE flag :

regx = re.compile("^DATA_ARRAY Some\[\].*?};", re.DOTALL|re.MULTILINE)



回答3:


If you add a re.MULTILINE flag it should work.

This will make the flags look like re.MULTILINE|re.DOTALL



来源:https://stackoverflow.com/questions/30485240/python-regex-does-not-match-line-start

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!