[BangPypers] A trivial doubt in negative lookbehind regular expression pattern

Senthil Kumaran orsenthil at gmail.com
Tue Apr 5 14:08:10 CEST 2011


On Tue, Apr 05, 2011 at 05:04:38PM +0530, Neha Jain wrote:
> I am trying to avoid matching of the terms that start with a word ABC_
> The general pattern is that the term has only caps alphabets and _, I have
> to ignore from these terms, ones that begin in ABC_
> The regular expression I have written is:
> 
> pattern = re.compile( ' ((?<!ABC_)([A-Z_]+) )' )

That is because your [A-Z_]+ will match the entire string and then it
the string does not start with ABC_ is still true.

How about using negative lookahead match at the start, by doing
something like this.

>>> m = re.search('^(?!ABC_)[A-Z_]+','ABC_CDF')
>>> m.group(0)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'NoneType' object has no attribute 'group'
>>> m = re.search('^(?!ABC_)[A-Z_]+','AB_CDF')
>>> m.group(0)
'AB_CDF'

-- 
Senthil


More information about the BangPypers mailing list