使用 Python 进行贪婪搜索时出现问题

Issue doing greedy search using Python

这是我的输入文本:“您可以选择 1、2 或 3 间卧室”

我想得到卧室的数量,所以在“卧室”之前有一个或多个数字(允许:',', '-', 'and', '&', 'or',和 'whitespace' 之间的数字)

我试过这种模式:(1|2|3|4|5|6|,|-|\s|&|and|or){1,12}bedroomregex101 上,效果很好。

但是我下面的 Python 代码不起作用:

text = "you have a choice between 1, 2 or 3 bedrooms"
number_range_pattern = r"(1|2|3|4|5|6|,|-|\s|&|and|or){1,12}"
bedrooms = re.search(number_range_pattern + r"bedroom", text)
if bedrooms and len(bedrooms.groups()) >= 1:
    match = bedrooms.group(1) # <-- match is a whitespace

结果:match 是 whitespce

我希望结果为:“1、2 或 3”

这是一个可行的解决方案:

text = "you have a choice between 1, 2 or 3 bedrooms"
m = re.search(r'\d+(?:,? (?:(?:and|or|&) )?\d+)*', text)
if m:
    print(m.group())  # 1, 2 or 3

此处的正则表达式模式可以使用解释:

\d+                   match a number
(?:
    ,?                optional comma separator
    [ ]               space
    (?:
        (?:and|or|&)  and, or, & conjunction
        [ ]           followed by space
    )?                and/or/& zero or one time
    \d+               another number
)*                    zero or more times

您需要 print(bedrooms.group(0)) 而不是 bedrooms.group(1)