python 正则表达式,怎么才能最小匹配?

Python016

python 正则表达式,怎么才能最小匹配?,第1张

把imgMatchs改成imgMatchs = re.finditer(r'\[.+?\]', s)

可以得出:

(3, 6)

(14, 17)

rre = re.compile(r'(.+?)(\[.+?\])(.+?)(\[.+?\])(.+)')

rre.findall(s)

可以得到

[('fds', '[d]', 'fsfsdafd', '[c]', 'safdsfsd')]

转换一下就可以满足要求了。

括号匹配最少添加python可以通过使用Python的栈数据结构来实现,代码如下:

```

def isValid(string):

stack = []

for char in string:

if char == '(':

stack.append(char)

elif char == ')':

if len(stack) == 0:

return False

stack.pop()

return len(stack) == 0

```