如何使用regexp获取嵌套组

时间:2016-10-28 06:39:15

标签: python regex nested-groups

我需要你的帮助才能使用正则表达式。 我有一个文字

"[Hello|Hi]. We are [inviting | calling] you at position [[junior| mid junior]|senior] developer."

使用正则表达式我想得到

[Hello|Hi]
[inviting | calling]
[[junior| mid junior]|senior]

以下rexeg (\[[^\[$\]\]]*\])

给了我 [Hello|Hi] [inviting | calling] [junior| mid junior]

那么我应该如何解决它以获得正确的输出?

3 个答案:

答案 0 :(得分:2)

让我们定义你的字符串并导入re:

>>> s = "[Hello|Hi]. We are [inviting | calling] you at position [[junior| mid junior]|senior] developer."
>>> import re

现在,试试:

>>> re.findall(r'\[ (?:[^][]* \[ [^][]* \])* [^][]*  \]', s, re.X)
['[Hello|Hi]', '[inviting | calling]', '[[junior| mid junior]|senior]']

更详细

考虑这个脚本:

$ cat script.py
import re
s = "[Hello|Hi]. We are [inviting | calling] you at position [[junior| mid junior]|senior] developer."

matches = re.findall(r'''\[       # Opening bracket
        (?:[^][]* \[ [^][]* \])*  # Zero or more non-bracket characters followed by a [, followed by zero or more non-bracket characters, followed by a ]
        [^][]*                    # Zero or more non-bracket characters
        \]                        # Closing bracket
        ''',
        s,
        re.X)
print('\n'.join(matches))

这会产生输出:

$ python script.py
[Hello|Hi]
[inviting | calling]
[[junior| mid junior]|senior]

答案 1 :(得分:2)

您可以使用简单的stack来代替recursive regex

x="[Hello|Hi]. We are [inviting | calling] you at position [[junior| mid junior]|senior] developer.[sd[sd[sd][sd]]]"
l=[]
st=[]
start=None
for i,j in enumerate(x):
    if j=='[':
        if j not in st:
            start = i
        st.append(j)
    elif j==']':
        st.pop()
        if not st:
            l.append(x[start:i+1])
print l

输出:['[Hello|Hi]', '[inviting | calling]', '[[junior| mid junior]|senior]', '[sd[sd[sd][sd]]]']

答案 2 :(得分:1)

您可以将以下代码与PyPi regex module一起使用,并使用类似PCRE的r'\[(?:[^][]++|(?R))*]'正则表达式:

>>> import regex
>>> s = "[Hello|Hi]. We are [inviting | calling] you at position [[junior| mid junior]|senior] developer."
>>> r = regex.compile(r'\[(?:[^][]++|(?R))*]')
>>> print(r.findall(s))
['[Hello|Hi]', '[inviting | calling]', '[[junior| mid junior]|senior]']
>>> 

请参阅regex demo

\[(?:[^][]++|(?R))*][匹配,然后匹配除][以外的1个字符的零个或多个序列或整个括号内的表达式[...],然后结束]