我想捕获彼此相邻的方括号/圆括号对,并捕获其中的单词。在下面的文本中,我想捕捉 [oh](so)
和 [bad](things)
。
[oh](so)funny
[all]the[bad](things)
如果我使用正则表达式 r'\[(.*?)\]\((.*?)\)'
它会捕获 [oh](so)
和 [all]the[bad](things)
,这不是我想要的。
什么是解决这个问题的好正则表达式?
最佳答案
不要使用.*?
。
改为使用 [^\]]+
和 [^\)]+
换句话说:
r'\[([^\]]+)\]\(([^\)]+)\)'
关于Python 正则表达式 : Matching bracket/parenthesis pairs,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12132336/