Help: Non-capturing RE fails?

roymath at my-deja.com roymath at my-deja.com
Mon Feb 12 17:09:46 CET 2001


Hi folks,

I don't know if it is my understanding of non-capturing REs thats flawed, or
there is a bug in CPython 2.0. Anyhow, the following test indicates what I
think is the problem:

Please email me as well at roymath at yahoo.com, as I dont always have access
to dejanews.

Thanks,
Roy.

# ----------------------------------------------------------------------
import re

str = r' - <<ba>> @<<b>> <<c>> - '
desiredResult = r" - ba @<<b>> c - "

# The following fails. produces: " -ba @<<b>>c - " (Note. whitespace is eaten
up). # Use non-capturing RE. r = re.compile(r'(?:[^@])<<(.*?)>>') print
re.sub(r, r"\1", str)

# The following succeeds. produces: " - ba @<<b>> c - "
# Use a named group instead of non-capturing RE

def mysub(x):
    # print x.groups()
    return x.group('ws') + x.group('pat')

r = re.compile(r'(?P<ws>[^@])<<(?P<pat>.*?)>>')
print re.sub(r, mysub, str)

# ------------------------------------------------------------------------


Sent via Deja.com
http://www.deja.com/



More information about the Python-list mailing list