簡體   English   中英

Python正則表達式匹配可能的單詞

[英]python regex match a possible word

我想匹配一個正則表達式來匹配一個可能不存在的單詞。 在這里讀到我應該嘗試這樣的事情:

import re

line = "a little boy went to the small garden and ate an apple"


res = re.findall("a (little|big) (boy|girl) went to the (?=.*\bsmall\b) garden and ate a(n?)",line)

print res

但是這個的輸出是

[]

如果我將line設置為

一個小男孩去花園里吃了一個蘋果

如何允許文本中可能存在的單詞存在或不存在,並在存在的情況下將其捕獲?

首先,您不僅需要匹配一個“小”字,還需要匹配一個空格(在此之后(或之前))。 因此,您可以像這樣使用正則表達式: (small )? 另一方面,您只想抓住這個詞。 要從捕獲中排除匹配項,您應使用如下正則表達式(?:(small) )?

完整示例:

import re

lines = [
    'a little boy went to the small garden and ate an apple',
    'a little boy went to the garden and ate an apple'
]

for line in lines:
    res = re.findall(r'a (little|big) (boy|girl) went to the (?:(small) )?garden and ate a(n?)', line)
    print res

輸出:

[('little', 'boy', 'small', 'n')]
[('little', 'boy', '', 'n')]

暫無
暫無

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

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