让我们定义你的字符串并导入 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]