I am processing equations using python regex.
I want to capture the repeating operands of the multiplication like below
5*5 --> 5
3.14*4 --> no return
(10-4)*(10-4) --> (10-4)
I found individual patterns to address the scenarios with or without parenthese
pattern = r"(?=(?:\D|\b))(\d+)\*\1(?=(?:\D|\b))"
re.findall(pattern, "15*15") # ['15']
re.findall(pattern, "3.14*4") # []
pattern = r"(\([\d\-\+]+\))\*\1"
re.findall(pattern, "(10-4)*(10-4)") # ['(10-4)']
But I found it's tricky that I cannot combine both patterns together,
either by alternation (|) or ? quantifier.
pattern = r"(?=(?:\D|\b))(\d+)\*\1(?=(?:\D|\b))|(\([\d\-\+]+\))\*\1" # Alternation
re.findall(pattern, "15*15") # [('15', '')]
re.findall(pattern, "3.14*4") # []
re.findall(pattern, "(10-4)*(10-4)") # []
pattern = r"(?=(?:\D|\b))(\(?[\d\-\+]+\)?)\*\1(?=(?:\D|\b))" # with ? for parenthese
re.findall(pattern, "15*15") # ['15']
re.findall(pattern, "3.14*4") # []
re.findall(pattern, "(10-4)*(10-4)") # []
Is there any workaround or should I have to do it seperately?