Add optional part in python regular expression
I want to add an optional part to my python expression:
myExp = re.compile("(.*)_(\d+)\.(\w+)")
so that if my string is abc_34.txt, result.group(2) is 34 if my string is
abc_2034.txt, results.group(2) is still 34
I tried myExp = re.compile("(.*)_[20](\d+)\.(\w+)")
but my results.groups(2) is 034 for the case of abc_2034.txt
Thanks F.J.
But I want to expand your solution and add a suffix.
so that if I put abc_203422.txt, results.group(2) is still 34
I tried "(.*)_(?:20)?(\d+)(?:22)?.(\w+)") but I get 3422 instead of 34
No comments:
Post a Comment