簡體   English   中英

正則表達式捕獲最多2位數字和逗號(如果后面跟另一個單詞和數字)

[英]Regex to capture numbers up to 2 digits and coma if followed by another word and number

我需要一個正則表達式來匹配並在滿足條件時從字符串中返回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

我會得到

8 and 13 / 13 and 8 / 13 and 13 / 8,8 / 13,5 and 5

我正在嘗試這個

\b([0-9][0-9]?)\s[y|\+]\s([0-9]{1,2})\shouses\b

但也無法獲得','。

您如果要將可選的十進制值與可選組匹配:

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

哪里(?:,[0-9])? 將匹配一個逗號,后跟一個數字(如果存在)。 請注意,我將數字匹配限制為0到29之間的值; 首先匹配可選的12 ,然后匹配0-9

演示:

>>> import re
>>> demo = '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'
>>> pattern = re.compile(r"\b([1-2]?\d(?:,\d)?)\s[y+]\s([1-2]?\d(?:,\d)?)\shouses\b")
>>> pattern.findall(demo)
[('8', '13'), ('13', '8'), ('13', '13'), ('8', '8'), ('13,5', '8')]

嘗試一下:

#! /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))

示范:

$ python pyregex.py 
found: 8 and 13
found: 13 and 8
found: 13 and 13
found: 8 and 8
found: 13,5 and 8

當該正則表達式與您輸入中的字符串匹配時,第一個數字將在match.group(1) ,第二個數字將在match.group(3)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM