昨天我一直在尝试各种各样的解决办法,直到挂断电话睡觉。今天回来再看一眼。。。我仍然不明白我的正则表达式有什么问题。你知道吗
我试图搜索我的库存基于一个简单的名称,并返回一个项目索引和数量的项目,我有。你知道吗
例如,在我的清单(而不是刀)中,我可以在0索引处使用血腥的\u刀[9],脚本应该根据刀的查询返回9和0。你知道吗
代码:
import re
inventory = ["knife", "bottle[1]", "rope", "flashlight"]
def search_inventory(item):
numbered_item = '.*' + item + '\[([0-9]*)\].*'
print(numbered_item) #create regex statement
regex_num_item = re.compile(numbered_item)
print(regex_num_item) #compiled regex statement
for x in item:
match1 = regex_num_item.match(x) #regex match....
print(match1) #seems to be producing nothing.
if match1: #since it produces nothing the code fails.
num_item = match1.group()
count = match1.group(1)
print(count)
index = inventory.index(num_item)
else: #eventually this part will expand to include "item not in inventory"
print("code is wrong")
return count, index
num_of_item, item_index = search_inventory("knife")
print(num_of_item)
print(item_index)
输出:
.*knife\[([0-9]*)\].*
re.compile('.*knife.*\\[([0-9]*)\\].*')
None
code is wrong
有一件事我似乎不能很好地解决,那就是python在我的numbered_item
变量中获取代码并在re.compile()
函数中使用它。既然我已经有了必要的[]
转义,为什么还要添加额外的转义呢。你知道吗
以前有人碰到过这样的事吗?你知道吗
您的问题是:
这就是“对于项目中的每个字符
knife
”。所以您的正则表达式是在k
上运行的,然后是n
,依此类推。你的正则表达式当然不会想要那样。如果您仍然想“看”,请添加打印x:您将看到它将打印项目的每个字母。这就是你在你的
match1 = regex_num_item.match(x)
中所要匹配的,所以很明显它不起作用。 您想迭代inventory
。你知道吗所以你想:
对你来说
index
重要吗?因为您可以将清单更改为字典,而不必使用regex:然后,如果你想找到每一个有
knife
这个词的项目,以及你有多少个:输出:
相关问题 更多 >
编程相关推荐