簡體   English   中英

Python:將正則表達式組組合成一個非分組形式的正則括號內的一個

[英]Python: Combining regular expression groups into one inside a non-grouping version of regular parentheses

以下代碼導致

>>> r = re.compile(r'(?:\|(.+?)|([a-z]+))<(.+?)>')
>>> print r.findall('hello, stack<overflow> / hello|fluid-<overflow>')
[('', 'stack', 'overflow'), ('fluid-', '', 'overflow')]

我想要的是[('stack', 'overflow'), ('fluid-', 'overflow')] 也就是說,我要忽略任何不匹配的組。 我該如何實現?

將您的正則表達式更改為:

r'((?<=\|).+?|[a-z]+)<(.+?)>'

使用后向斷言管道字符| ,但不將其包含在主比賽中。

像這樣:

>>> re.findall(r'(?:([^|\s]+)<(.+?)>)', 'hello, stack<overflow> / hello|fluid-<overflow>')
[('stack', 'overflow'), ('fluid-', 'overflow')]

暫無
暫無

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

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