python - 正则表达式在表达式中查找变量
问题描述
我正在寻找一个匹配表达式中所有变量的正则表达式,它只能是字母后跟数字,如“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] 表示“不是一个字母后跟一个字母本身后跟一个字母”,但它似乎不起作用,它返回给我一个 [] 列表
解决方案
利用
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']
推荐阅读
- java - 打开前置摄像头
- javascript - 将路径数组转换为对象数组分组
- r - 如何在 R 中自定义效果图?
- javascript - 将国家代码电话前缀转换为 ISO 3166-1 alpha-2 格式
- python - 如何在不重新加载页面的情况下根据选择字段中的选定值在网页上显示图像
- android - Mapbox 在 Android O 上不显示地图
- testing - 将 TestCafe 与 mobx 一起使用
- office-js - 在 Outlook 和加载项窗格之间拖放
- ios - 如何正确获取一组 EKCalendars
- python - 使用 REST API 从 Python 脚本请求数据