regular expression back references

John Machin sjmachin at lexicon.net
Fri Aug 8 21:38:17 EDT 2003


ruach at chpc.utah.edu (Matthew) wrote in message news:<ec1162c7.0308081412.4c0d2fca at posting.google.com>...
> 
> Here is my patteren:
> 
> macExpression = "^[0-9A-F]{1,2}(\:|\.|\-)[0-9A-F]{1,2}\1[0-9A-F]{1,2}\1[0-9A-F]{1,2}\1[0-9A-F]{1,2}\1[0-9A-F]{1,2}$:
> 
> And this is how I am using it:
> 
> matched = re.match(macExpression, macAddress)
> 
> I am trying to match mac addresses in the following formats
> 0:a0:c9:ee:b2:c0, 0-a0-c9-ee-b2-c0 & 0.a0.c9.ee.b2.c0 etc.
> 

Four problems (1) Your pattern has 5 occurrences of [0-9-A-F] but your
data has 6 (2) your pattern has uppercase hex digits but your data has
lowercase (3) you need to double some backslashes or (preferably) use
the r"..." notation (4) your pattern is missing the trailing " -- it
helps if you cut and paste when posting rather than re-typing stuff.

and one superfluity: the "^" at the start is redundant

The following appears to work:

>>> macExpression = r"[0-9A-F]{1,2}(\:|\.|\-)([0-9A-F]{1,2}\1){4,4}[0-9A-F]{1,2}$"
>>> for macAddr in ["0:a0:c9:ee:b2:c0", "0-a0-c9-ee-b2-c0",
"0.a0.c9.ee.b2.c0", "0:a0-c9:ee:b2:c0"]:
...    print re.match(macExpression, macAddr, re.I)
...
<_sre.SRE_Match object at 0x007C8818>
<_sre.SRE_Match object at 0x007C8818>
<_sre.SRE_Match object at 0x007C8818>
None




More information about the Python-list mailing list