簡體   English   中英

正則表達式僅返回比賽的第一部分

[英]Regex only returning first part of match

我想從這句話中提取the catanother mat

>>> text = "the cat sat on another mat"
>>> 
>>> re.findall('(the|another)\s+\w+', text)
['the', 'another']

但是它不會返回后面的catmat 如果我將其更改為re.findall('another\\s+\\w+', text)那么它將找到該部分,但是為什么(first thing | second thing)不起作用?

(使用Python的re模塊)

我會做

import re
text = "the cat sat on another mat"

re.findall('the\s+\w+|another\s+\w+', text)

結果應該是

>>> ['the cat', 'another mat']

如果捕獲組存在於給定的正則表達式模式中,則re.findall僅返回捕獲組中的子字符串,因此在這種情況下,您應該使用非捕獲組,這樣re.findall將返回整個匹配項:

re.findall('(?:the|another)\s+\w+', text)

返回:

['the cat', 'another mat']

暫無
暫無

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

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