Regular Expressions 101

Community Patterns

Replace ^ with Math.pow function. Not made to work with braces.

1

Regular Expression
Java 8

"
(-?[.0-9]+)\^(-?[.0-9]+)
"
gm

Description

Replaces ^ with Math.pow function call. This assumes all braces have been combined first. If you need help with the combination, I got you—try this Python algorithm:

def evaluate_braces(expr):
    """Recursively evaluate expressions within braces"""
    # Check if expression contains braces
    if '(' in expr:
        # Find the innermost set of braces
        left = expr.rfind('(')
        right = left + expr[left:].find(')')
        # Evaluate the expression within the braces
        result = eval(expr[left+1:right])
        # Replace the expression within the braces with its result
        expr = expr[:left] + str(result) + expr[right+1:]
        # Recursively evaluate any remaining expressions within braces
        expr = evaluate_braces(expr)
    # Evaluate the final expression
    return expr

expression = "31+((4+1)+2*7)*2"
result = evaluate_braces(expression)
print(result) # Output: 2+2+3+4*8/2
Submitted by Glitchii - https://github.com/Glitchii - a year ago (Last modified a year ago)