Consider this (very simplified) example string:
1aw2,5cx7
As you can see, it is two digit/letter/letter/digit
values separated by a comma.
Now, I could match this with the following:
>>> from re import match
>>> match("\d\w\w\d,\d\w\w\d", "1aw2,5cx7")
<_sre.SRE_Match object at 0x01749D40>
>>>
The problem is though, I have to write \d\w\w\d
twice. With small patterns, this isn't so bad but, with more complex Regexes, writing the exact same thing twice makes the end pattern enormous and cumbersome to work with. It also seems redundant.
I tried using a named capture group:
>>> from re import match
>>> match("(?P<id>\d\w\w\d),(?P=id)", "1aw2,5cx7")
>>>
But it didn't work because it was looking for two occurrences of 1aw2
, not digit/letter/letter/digit
.
Is there any way to save part of a pattern, such as \d\w\w\d
, so it can be used latter on in the same pattern? In other words, can I reuse a sub-pattern in a pattern?