首页 > 解决方案 > 正则表达式在表达式中查找变量

问题描述

我正在寻找一个匹配表达式中所有变量的正则表达式,它只能是字母后跟数字,如“x1”或不后跟数字,如“z”。我想在表达式中找到它们,它们后面可以跟所有字符,例如

expr = exp(x36)+log(x27)+2*z

例如,正则表达式应该返回 [x36, x27, z]

我试过这个:

pattern = re.findall("[^a-z][a-z][^a-z](\d?)", expr)

其中 [^az][az][^az] 表示“不是一个字母后跟一个字母本身后跟一个字母”,但它似乎不起作用,它返回给我一个 [] 列表

标签: pythonregex

解决方案


利用

re.findall(r'\b[A-Za-z]\d*\b', exp)

请参阅正则表达式证明

解释

--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char
--------------------------------------------------------------------------------
  [A-Za-z]                 any character of: 'A' to 'Z', 'a' to 'z'
--------------------------------------------------------------------------------
  \d*                      digits (0-9) (0 or more times (matching
                           the most amount possible))
--------------------------------------------------------------------------------
  \b                       the boundary between a word char (\w) and
                           something that is not a word char

蟒蛇代码

import re
regex = r"\b[A-Za-z]\d*\b"
test_str = "exp(x36)+log(x27)+2*z"
print(re.findall(regex, test_str))

结果['x36', 'x27', 'z']


推荐阅读