Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex does not match line start

Tags:

python

regex

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.

like image 892
ele lont Avatar asked Jul 31 '26 21:07

ele lont


2 Answers

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)
like image 84
Mazdak Avatar answered Aug 03 '26 11:08

Mazdak


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

regx = re.compile("^DATA_ARRAY Some\[\].*?};", re.MULTILINE|re.DOTALL)
like image 26
karthik manchala Avatar answered Aug 03 '26 11:08

karthik manchala



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!