python - 从字符串输入中过滤元素
问题描述
给出以下字符串:
mystring = "animals.dog > 12 and type.type_id=105 and colors.name='yellow'"
我想从此字符串返回以下元素。
table1 = animals
element1 = dog
operator1= greater
table2 = type
element2 = type_id
operator2= equal
table3 = colors
element3 = name
operator3 = equal
我只对前 3 部分感兴趣,即 table.element 运算符(例如 animals.dog>)
不幸的是,我已经将句子转换为列表失败了
我目前尝试了以下方法,但是使用这种方法,操作符不会被阅读。
import re
mystring = "animals.dog > 12 and type.type_id=105 and colors.name='yellow'"
wordList = re.sub("[^\w]", " ", mystring).split()
如果你能帮我解决这个问题,我会很高兴。此致
解决方案
这是适用于此示例的正则表达式:
out = re.findall("([^\W]+)\.([^\W]+)\W*([<>=])", mystring)
输出:
[('animals', 'dog', '>'), ('type', 'type_id', '='), ('colors', 'name', '=')]
但它不支持>=
or之类的运算符<=
。如果您需要它们,则需要在正则表达式中指定它们。
有了输出列表,您可以像这样迭代它:
for table, element, operator in out:
...
推荐阅读
- python - 如何使用内部函数返回的结果作为外部函数的参数?
- javascript - 从 JS 中的多维数组中突围——特定的 2 个问题
- c# - ASP.NET Core 项目中的 MySql 连接字符串错误
- mongodb - 当完整文档中的字段具有特定值时,MongoDB 领域触发
- c# - 移动滑块时如何播放音频剪辑?
- tensorflow - 为什么使用 CNN 进行时间序列预测时 x 大小和 y 大小必须相同?
- angular - 在角度编译器之前编辑打字稿
- mysql - 使用正则表达式从 MySQL 中的 URL 中提取主机名
- c - 如何在 C python 扩展中使用 PyObject* args?
- php - Laravel 自动上传文件并链接到模型