Regex捕获最多2位数的数字,如果后面跟着另一个单词,则会昏迷

2024-10-03 23:26:41 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要一个正则表达式,匹配并在满足条件时从字符串返回2个数字

  1. 仅限最大为2位数且不大于29的数字(可能包括十进制大小写-因此最多2位数加上1个十进制大小写)

  2. 它们必须在y+中的一个字符之间,在第二个数字之后是单词“houses”

然后捕捉两个数字

对于以下字符串:

8 y 13 houses, 13 y 8 houses, 13 y 13 houses, 8 y 8 houses, 120 y 8 houses, 8 y 120 houses, 13,5 y 8 houses, 13,5 y 120 houses

我会得到

^{pr2}$

我试着用这个

^{3}$

但也没办法得到','。在


Tags: 字符串数字字符单词我会位数办法pr2
2条回答

试试看:

#! /usr/bin/env python

import re

str = '8 y 13 houses, 13 y 8 houses, 13 y 13 houses, 8 y 8 houses, 120 y 8 houses, 8 y 120 houses, 13,5 y 8 houses, 13,5 y 120 houses'

regex = r'''
\b (
    [012]?     # number may go up to 29, so could have a leading 0, 1, or 2
    [0-9]      # but there must be at least one digit 0-9 here
    (,[0-9])?  # and the digits might be followed by one decimal point
)
\s* [y+] \s*   # must be a 'y' or '+' in between
(
    [012]?     # followed by another 0-29
    [0-9]
    (,[0-9])?  # and an optional decimal point
)
\s* houses \b  # followed by the word "houses"
'''

for match in re.finditer(regex, str, re.VERBOSE):
    print "found: %s and %s" % (match.group(1), match.group(3))

演示:

^{pr2}$

当正则表达式与输入中的字符串匹配时,第一个数字将位于match.group(1)中,第二个数字将位于match.group(3)中。在

如果要将可选十进制值与可选组匹配,请执行以下操作:

re.compile(r"\b([1-2]?\d(?:,\d)?)\s[y+]\s([1-2]?\d(?:,\d)?)\shouses\b")

其中(?:,[0-9])?将匹配逗号后跟数字(如果存在)。注意,我将数字匹配限制为0到29之间的值;首先匹配可选的1或{},然后是{}。在

演示:

^{pr2}$

相关问题 更多 >