python用正则对字符串进行运算

import re


def nul_div(source):
    """
    处理乘法和除法,先利用搜索出需要进行乘法和除法的表达式,然后利用正则将字符串分割,进行乘法和除法的运算
    :param source: 要进行计算的字符串
    :return: 将计算过的表达式替换到原有字符串,返回计算后的字符串
    """
    source = str_format(source)
    while re.search('*|/', source):
        ret = re.search('[. 0-9]+?[*/][+-]?[. 0-9]+', source).group()
        res_data = re.findall('(-?[d.]+|*|/)', ret)
        if res_data[1] == '*':
            res = float(res_data[0]) * float(res_data[2])
        else:
            res = float(res_data[0]) / float(res_data[2])
        source = source.replace(ret, str(res))
    return source


def add_sub(source):
    """
    处理加法和减法,先利用搜索出需要进行加法和减法的表达式,然后利用正则将字符串分割,进行加法和减法的运算
    :param source: 要进行计算的字符串
    :return: 将计算过的表达式替换到原有字符串,返回计算后的字符串
    """
    source = str_format(source)
    while re.search('[+-]?[.0-9]*[+-]+[.0-9]*', source):
        ret = re.search('[+-]?[.0-9]*[+-]+[.0-9]*', source).group()
        res_data = re.findall(r'([d.]+|+|-)', ret)
        if len(res_data) == 2:
            if res_data[0] == '-':
                res = -float(res_data[1])
            else:
                res = float(res_data[1])
            source = source.replace(ret, str(res))
            return source
        elif len(res_data) > 2:
            if res_data[0] == '-':
                if res_data[2] == '-':
                    res = - float(res_data[1]) - float(res_data[3])
                else:
                    res = - float(res_data[1]) + float(res_data[3])
            elif res_data[0] == '+':
                if res_data[2] == '-':
                    res = float(res_data[1]) - float(res_data[3])
                elif res_data[2] == '+':
                    res = float(res_data[1]) + float(res_data[3])
                else:
                    res = float(res_data[1])
            else:
                if res_data[1] == '-':
                    res = float(res_data[0]) - float(res_data[2])
                else:
                    res = float(res_data[0]) + float(res_data[2])
        else:
            res = float(res_data[0])
            source = source.replace(ret, str(res))
            return source
        source = source.replace(ret, str(res))
    return source


# def add_sub(source):
#     """
#     处理加法和减法,先利用搜索出需要进行加法和减法的表达式,然后利用正则将字符串分割,进行加法和减法的运算
#     :param source: 要进行计算的字符串
#     :return: 将计算过的表达式替换到原有字符串,返回计算后的字符串
#     """
#     source = str_format(source)
#     while re.search('[. 0-9]+?[+-][. 0-9]+', source):
#         ret = re.search('[+-]?[.0-9]+?[+-][. 0-9]+', source).group()
#         print(ret)
#         res_data = re.findall(r'([d.]+|+|-)', ret)
#         print(res_data)
#         if res_data[0] == '-':
#             if res_data[2] == '-':
#                 res = - float(res_data[1]) - float(res_data[3])
#             else:
#                 res = - float(res_data[1]) + float(res_data[3])
#         elif res_data[0] == '+':
#             if res_data[2] == '-':
#                 res = float(res_data[1]) - float(res_data[3])
#             else:
#                 res = float(res_data[1]) + float(res_data[3])
#         else:
#             if res_data[1] == '-':
#                 res = float(res_data[0]) - float(res_data[2])
#             else:
#                 res = float(res_data[0]) + float(res_data[2])
#         source = source.replace(ret, str(res))
#     return source


def check_expression(source):
    """
    检查字符串是否可以进行正常计算,看括号是否相等,是否含有字母
    :param source: 要进行计算的字符串
    :return: 如果不能正常进行计算返回False,否则返回True
    """
    check_result = True
    if not source.count('(') == source.count(')'):
        print('表达式错误!请检查表达式中"("")"是否相等')
        check_result = False
    if re.findall('[a-z]', source.lower()):
        print('表达式错误!请检查表达式中是否含有字母')
        check_result = False
    return check_result


def str_format(source):
    """
    对字符串进行简单的替换,替换空格和加减法的符号
    :param source: 要进行替换的字符串
    :return: 返回替换后的字符串
    """
    source = source.replace(' ', '')
    source = source.replace('++', '+')
    source = source.replace('+-', '-')
    source = source.replace('-+', '-')
    source = source.replace('--', '+')
    return source


def str_calculation(source):
    """
    计算字符串,先判断是否可以计算,然后进行简单的替换,判断是否含有括号,进行计算
    :param source: 要进行计算的字符串
    :return: 返回计算结果
    """
    if check_expression(source):
        data = str_format(source)
        while re.search('(', data):
            r_data = re.search('([^()]+)', data).group()
            data_r = nul_div(r_data)
            data_r = add_sub(data_r)
            data = str_format(data.replace(r_data, data_r[1:-1]))
        else:
            data_r = nul_div(data)
            data_r = add_sub(data_r)
            data = str_format(data.replace(data, data_r))
    return data

if __name__ == '__main__':
    s = "1 - 2 * ( (60-30 +(-40/5) * (9-2*5/3 + 7 /3*99/4*2998 +10 * 568/14 )) - (-4*3)/ (16-3*2) )"
    s1 = '1-2*((60-30-8.0*(9-2*5/3+7/3*99/4*2998+10*568/14))-(-4*3)/(16-3*2))'
    s2 = '--9'
    print(str_calculation(s))
    print(eval(s))
    print(str_calculation(s1))
    print(eval(s1))
    print(str_calculation(s2))
    print(eval(s2))
原文地址:https://www.cnblogs.com/chen/p/11661811.html