How to get nested groups with regex

I need your help with the next regex. I have text

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

using regex I want to get

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

next rexeg (\[[^\[$\]\]]*\])

gives me [Hello|Hi] [inviting | calling] [junior| mid junior]

so how should I fix this in order to get the correct conclusion?

+4
source share
3 answers

Define your string and reimport:

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

Now try:

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

More details

Consider this script:

$ 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))

This leads to the output:

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

To do this, you can use simple stackinsteadrecursive 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

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

+2
source

PyPi regex PCRE r'\[(?:[^][]++|(?R))*]' regex:

>>> 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.

\[(?:[^][]++|(?R))*]matches [, then, zero or more sequences of 1+ characters other than ]and [OR the entire expression enclosed in square brackets [...], and then closing ].

+1
source

Source: https://habr.com/ru/post/1659143/


All Articles