我正在寻找一种从字符串中提取子字符串的方法,如果它位于某个标识符之前。在
string = [food(type, description), newCar(make, year), fruit(shape, colour), usedCar(make, year), ..., identifier(str1, str2)]
identifier = car (newCar and/or usedCar) - extract if both appear or either one appear
Desired outcome
identifier: newCar
first attribute = make
second attribue = year
identifier: usedCar
first attribute = make
second attribue = year
这是我尝试过的,但我似乎只得到了第一次出现的(…)。有什么办法来解决这个问题,如果我能把单个的字符串也放在括号里会更好吗?在
^{pr2}$编辑: 谢谢你的回复。我没有考虑Dict的一个原因是键必须是唯一的,而且我有一个多行的文本,在同一行中可能有重复的newCar条目。括号内的文字只是通用术语,因为它可能表示make=Toyota/Ford或year=2010/2013。在
这肯定不是最好的解决办法,但它是有效的。在
如果要使用标识符查找属性,可以使用dict
使用正则表达式:
如果您已经知道标识符将有一个
^{pr2}$make,year
对,您也可以提取它们:你想怎么做就怎么做。尽管如此,还是有更好的方法来做到这一点。您可以将项目存储为键:值对例如使用字典。在
相关问题 更多 >
编程相关推荐