Python regex doesn't match beginning of line

I have a text file with some data:

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

      

and I have 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 doesn't match anything (regmatch is None). If I remove the ^, then it only matches the fine.

What am I doing wrong here? I would like to add a start-of-line character.

+3


source to share


3 answers


^

checks the beginning of a line .. add a flag re.MULTILINE

.



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

      

+1


source


the modifier^

forces your regex engine to match the regex from the beginning of the line. 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 the flag re.MULTILINE

:



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

      

+5


source


If you add a flag re.MULTILINE

it should work.

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

+2


source







All Articles