[英]Regex only returning first part of match
我想從這句話中提取the cat
和another mat
:
>>> text = "the cat sat on another mat"
>>>
>>> re.findall('(the|another)\s+\w+', text)
['the', 'another']
但是它不會返回后面的cat
和mat
。 如果我將其更改為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.