Python:如何使用正则表达式获取所有可能的匹配

时间:2018-11-01 20:04:47

标签: python regex python-3.x

我试图在括号之间找到文本,但我想要这样的东西

 s="( abc (def) kkk ( mno) sdd ( xyz ) )"
 p=re.findall(r"\(.*?\)",s)
    for i in p:
        print(i)

输出:

( abc (def) ,
( mno),
( xyz )

预期:

( abc (def) ,
( abc (def) kkk ( mno) ,
( abc (def) kkk ( mno) sdd ( xyz ) ,
( abc (def) kkk ( mno) sdd ( xyz ) ) ,
(def) ,
(def) kkk ( mno)  ,
(def) kkk ( mno) sdd ( xyz ) ,
(def) kkk ( mno) sdd ( xyz ) ) ,
( mno) ,
( mno) sdd ( xyz ) ,
( mno) sdd ( xyz ) ) ,
( xyz ) ,
( xyz ) ) 

1 个答案:

答案 0 :(得分:1)

python regex模块不处理重叠的匹配项。通过在文本中找到()的位置,为开始/结束值创建明智的元组并对字符串进行切片,更容易获得

使用enumerate(iterable)collections.defaultdict()itertools.product()

s="( abc (def) kkk ( mno) sdd ( xyz ) )"

# get positions of all opening and closing ()
from collections import defaultdict
d = defaultdict(list)
print(d)

for idx,c in enumerate(s):
    if c in "()":
        d[c].append(idx)

# combine all positions 
from itertools import product
pos = list(product (d["("],d[")"]))
print(pos)

# slice the text if start < stop+1 else skip
for start,stop in pos:
    if start < stop+1:
        print(s[start:stop+1])

输出:

# d
defaultdict(<class 'list'>, {'(': [0, 6, 16, 27], ')': [10, 21, 33, 35]})

# pos
[(0, 10), (0, 21), (0, 33), (0, 35), (6, 10), (6, 21), (6, 33), (6, 35), 
 (16, 10), (16, 21), (16, 33), (16, 35), (27, 10), (27, 21), (27, 33), (27, 35)]

# texts from pos
( abc (def)
( abc (def) kkk ( mno)
( abc (def) kkk ( mno) sdd ( xyz )
( abc (def) kkk ( mno) sdd ( xyz ) )
(def)
(def) kkk ( mno)
(def) kkk ( mno) sdd ( xyz )
(def) kkk ( mno) sdd ( xyz ) )
( mno)
( mno) sdd ( xyz )
( mno) sdd ( xyz ) )
( xyz )
( xyz ) )