首页 > 解决方案 > 从字符串输入中过滤元素

问题描述

给出以下字符串:

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()

如果你能帮我解决这个问题,我会很高兴。此致

标签: pythonstringlistreturn

解决方案


这是适用于此示例的正则表达式:

out = re.findall("([^\W]+)\.([^\W]+)\W*([<>=])", mystring)

输出:

[('animals', 'dog', '>'), ('type', 'type_id', '='), ('colors', 'name', '=')]

但它不支持>=or之类的运算符<=。如果您需要它们,则需要在正则表达式中指定它们。

有了输出列表,您可以像这样迭代它:

for table, element, operator in out:
    ...

推荐阅读