在python中使用正则表达式从字符串表达式中提取变量名

bin*_*.py 0 python regex string algebra formula

我在字符串中有一个代数表达式。我想从表达式中提取变量名。变量名应遵循python变量命名规则。(应该是字母或数字的组合,不应以数字开头,可以有下划线等)

例子:

formula = 'value1 * 5 + value_2 /4'
Run Code Online (Sandbox Code Playgroud)

它应该给出一个结果 ['value1', 'value_2']

Jon*_*nts 7

如果可能的话,我会使用ast解析 Python 代码本身的模块而不是正则表达式。这意味着您不必担心字符串文字/其他内容,如果解析失败,您将收到一个错误,这意味着它是一个不完整或无效的语句:

import ast

formula = 'value1 * 5 + value_2 /4'
names = [
    node.id for node in ast.walk(ast.parse(formula)) 
    if isinstance(node, ast.Name)
]
# ['value1', 'value_2']
Run Code Online (Sandbox Code Playgroud)