Python中导入Sympy后re.search正则匹配失效问题求助
问题:导入Sympy库后正则表达式匹配失效?
我编写了如下Python代码:
import re import math #from sympy import * # breaks? #x, y, z = symbols('x y z') #init_printing(use_unicode=True) def evaluate_expression(expr, variables): # Evaluate the expression using eval(), and provide the variables dictionary return eval(expr, variables) def main(): tools = """ <<<[eval("5"),a_x]>>> <<<[eval("5+a_x"),ans]>>> """ variables = {} lines = tools.strip().split("\n") for line in lines: # Extract the inner array using regular expression match = re.search(r'<<<\[(.*?),(\w+)\]>>>', line) if match: # Extract expression and variable name expr = match.group(1) var_name = match.group(2) # Evaluate expression value = evaluate_expression(expr, variables) # Update variables dictionary variables[var_name] = value # Check if 'ans' is defined if 'ans' in variables: print("ans =", variables['ans']) break if __name__ == "__main__": main()
未导入Sympy库时代码运行正常,可通过re.search提取表达式并完成计算;但取消注释导入Sympy的相关代码后,re.search无法匹配内容,无论如何命名变量都会出现问题,请问这是什么原因?
解答
实际不是re.search匹配失败,而是导入Sympy时覆盖了Python内置的eval函数,导致表达式执行抛出异常,程序提前终止,看起来像是匹配失效。
具体原因:
from sympy import *会导入Sympy自带的eval函数,这个函数和Python内置eval的参数要求完全不同。你的代码中,evaluate_expression里调用的eval(expr, variables),当expr是eval("5")时,实际调用的是Sympy的eval,它无法处理这种参数格式,直接抛出异常,但你的代码没有捕获异常,导致程序在第一次匹配后就崩溃,没有继续执行后续逻辑,给你造成了“正则没匹配到”的错觉。
解决办法:
避免全局导入Sympy:不要用
from sympy import *,改为按需导入需要的函数,比如:import sympy x, y, z = sympy.symbols('x y z') sympy.init_printing(use_unicode=True)或者:
from sympy import symbols, init_printing x, y, z = symbols('x y z') init_printing(use_unicode=True)这样就不会覆盖内置的
eval函数。明确指定使用内置eval:如果一定要用全局导入,在
evaluate_expression里明确调用Python内置的eval:def evaluate_expression(expr, variables): return __builtins__.eval(expr, variables)
内容的提问来源于stack exchange,提问作者Vatsa Pandey
相关产品推荐
相关产品推荐

