Reputation: 113
I would like to isolate all operands from a formula (in the form of a string) by taking out the arithmetic operators so take out: "+","-","/","*","**2" the formula string is something like:
"y=A+B1*options+B2*items**2+B3*factor+B4"
However: I can manage for most arithmetic operators, except for the exponents "**2" part. It has to be a wildcard search or so (not positional), because the whole formula might change in future and also might have another exponent (eg **5 or **54)
What would be the easiest way to strip "**?" out of the formula where ? can be any number?
Upvotes: 0
Views: 145
Reputation: 76
To match the pattern you want, use the regex string r"\*\*\d+"
Breakdown:
r""
is the how one denotes regex in python (see the re
module for more info)\*
matches a single *
character - because the *
is a special character in regex, we escape it with the \
\d
matches a digit+
matches the previous pattern at least once greedily: this means it will try to find at least one digit, then keep finding digits until it can find no more. So, it will match **2
, **44382
, and so onAs for stripping the pattern from the equation, you can do re.sub(pattern, "", equation)
- replacing all instances of the pattern with nothing
Upvotes: 1