# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"\[(b|i|u|h1|h2|h3|large|small|list|table|grid)\](?:((?!\[\/\1\]).)*?|(?R))*\[\/\1\]"
test_str = ("[b]the problem is that my [i]regex[/i] stops at the [b]first matching closing tag[/b] instead of matching recursively as i [u]expect it to.[/u] [/b]\n"
"[i]regex[/i] stops at the [b]first matching closing tag[/b] instead of matching recursively as i [u]expect it to.[/u]\n\n"
"[a]ssss[a]sssss[/a]ss[/a]\n\n"
"[b]sss[/b]\n\n"
"[c]asdfasd[d]asdaf[/d]fasdf[/c]\n\n"
"[i]test test [i]as fd[/i]this should match the whole line[/i]\n\n"
"[i]test test[j]this should match the whole line[/j]test[/i]\n\n"
"[i] test [j]this should match the pair of 'i' tags and ignore the second 'j' tag [/i] [/j]\n\n"
"the below line should have three sets of matches: center, h3, and grid; it only matches the h3 and grid tags\n"
"[center][logo][/center][hr][hr][h3]header[/h3][/center][hr][hr][grid][row][cell][b]some label[/b][cell]: [date][/grid]\n\n")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html