首页 > 解决方案 > 如何将多个变量传递给常规(re.search)表达式

问题描述

我正在尝试使用正则表达式(re.search)传递变量,但我似乎无法使用下面的代码成功地将信息读入等match.group(1)(2)有人可以快速看看我哪里出错了吗?

serial = 'abcdeID:11111abcdePR:22222abcde'

id = 11111
pr = 22222

match =  re.search(r'ID:{0}PR:{1}'.format(id, pr), serial)
print("ID value returned = " + match.group(1))
print("PR value returned = " + match.group(2))

#output
#AttributeError: 'NoneType' object has no attribute 'group'

标签: pythonregexpython-3.x

解决方案


您的正则表达式中没有组(...),因此不会返回它们。像这样添加它们:

match =  re.search(r'ID:({0})PR:({1})'.format(id, pr), serial)

推荐阅读