Aiogram结合re正则编写匹配id|name|cost格式的消息处理handler
Aiogram 按id|name|cost格式拆分消息字段的实现方案
原代码的问题在于拆分字段时的正则规则都是从头匹配,无法正确提取三个分隔后的字段,可按如下方式调整:
调整后完整代码
@dp.message_handler(AdminFilter(), state="get price", # 正则新增捕获组,直接匹配三个字段,提前做格式校验 regexp=re.compile(r"^(\d+)\|(.+?)\|(\d+)$")) async def get_price(message: types.Message, state: FSMContext): # 直接从aiogram自动生成的正则匹配结果中取分组值 match = message.regexp_match # 用strip清除字段前后可能存在的多余空格 item_id = match.group(1).strip() item_name = match.group(2).strip() item_cost = match.group(3).strip() await message.answer( f"""Товар добавлен: id: {item_id} name: {item_name} cost: {item_cost} """ )
备选实现(无需修改handler正则)
如果你不想修改原有handler的正则校验规则,也可以直接对消息文本做split拆分:
@dp.message_handler(AdminFilter(), state="get price", regexp=re.compile(r"^[0-9]*\|.*\|[0-9]*$")) async def get_price(message: types.Message, state: FSMContext): # 按|拆分后清除每个字段的前后空白,再解包赋值给三个变量 item_id, item_name, item_cost = [part.strip() for part in message.text.split('|')] await message.answer( f"""Товар добавлен: id: {item_id} name: {item_name} cost: {item_cost} """ )
注意事项
- 不要用
id作为变量名,id是Python内置函数,重名会导致潜在逻辑异常 - 两种方式都依赖原有handler的正则校验保证消息符合三段|分隔的格式,不会出现拆分后字段数量不足的问题
内容的提问来源于stack exchange,提问作者sata mems
相关产品推荐
相关产品推荐

