Reputation: 2398
Hi this is the string I want to match
mystr = "mykey/20161010/20161010"
so far my regex
is like this
re.match("mykey/([2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])/[.]*", mystr)
As you can see, I am using One Capture group
. I want to replace the [.]*
by referring the Capture group I have already created. How should I do this?
PS : I am using Python 2.7
Update 1 Based on the answers so far, I have tried this(I have simplified the example little bit), but does not seem to be working...
>>> mystr = "mykey/20/20"
>>> print re.match("mykey\/([2-9][0-9])\/[.]*", mystr)
<_sre.SRE_Match object at 0x7faf96ddf558>
>>> print re.match("mykey\/([2-9][0-9])\/.*", mystr)
<_sre.SRE_Match object at 0x7faf96ddf558>
>>> print re.match("mykey\/([2-9][0-9])\/\1", mystr)
None
I am getting None
when trying to refer the Capture group
. Am I missing something?
Update 2: Finally Working...
Hope this helps someone looking for the answer. Adding additional backslash(ie \)
did the trick
>>> import re
>>> mystr = "mykey/20160610/20160610"
>>> re.match("mykey/([2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])/\\1", mystr)
<_sre.SRE_Match object at 0x7fe352145558>
Upvotes: 0
Views: 217
Reputation: 49260
mykey\/([2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9])\/\1
Use \1
- to capture the exact match produced by the first capturing group which is [2-9][0-9][0-9][0-9][0-1][0-9][0-3][0-9]
in this case.
Shorter version of the same would be
mykey\/([2-9]\d{3}[0-1]\d[0-3]\d)\/\1
Upvotes: 2