在 Python 中与 re 进行多次匹配

Multiple matches with re in Python

我正在开发一个程序,我需要帮助来匹配列表中的现有单词。 我想做的是找到列表中单词前面的数字。但是列表有多个单词。该程序应该尝试这些单词,直到找到数字。 我已经试过了,但没有帮助我。请帮忙。

代码:

import re
time = ['o\'clock', 'o clock']

# If str == 'reminder at 17 o'clock
# Program finds 17
# But if str equals this:

str = 'reminder at 17 o clock'
for a in time:
    gettime = re.findall(fr'(\b\d+\b) {a}', str)
    gettime ''.join(gettime)
    gettime = int(gettime)

print(gettime)

代码报错,即Invalid literal for int() with base 10: ''

如何运行这两个字的程序。 o'clocko clock

此示例可能会给出您期望的结果:

import re
time = ['o\'clock', 'o clock']

# If str == 'reminder at 17 o'clock
# Program finds 17
# But if str equals this:

str = "reminder at 17 o'clock or 18 o clock"
times = []
for a in time:
    result = re.findall(fr'(\b\d+\b) {a}', str)
    #print(result)
    for i in result:
        itime = int(i)
        times.append(itime)

print(times)

这应该显示:

[17, 18]