# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^(?:\[[^\]\[\n]*\]\s+)?(?<name>[^)(\n]*)\s*(\([^)(\n]*\))?\s*(\([^)(\n]*\))?"
test_str = ("[Example] öäüß asdf 1234 (1aö)\n"
"[Red] Panda (It's so cute)\n"
"[Red] The Panda (It's so cute),\n"
"[Red] what Panda (It's so cute) (not necessary),\n"
"[Red] it's a Panda (It's so cute) (unusual),\n"
"[Yellow] Leopard (the big one)\n"
"[Yellow] The Leopard (the big one),\n"
"[Yellow] what Leopard (the big one) (not needed),\n"
"[Yellow] it's a Leopard (the big one) (unusual),\n"
"[Green] Dragon (Fire? It's hot!)\n"
"[Green] The Dragon (Fire? It's hot!),\n"
"[Green] what Dragon (Fire? It's hot!) (not usual),\n"
"[Green] it's a Dragon (Fire? It's hot!) (unusual),\n"
"[Blue] Snake (zzzZZZzzzZZZ)\n"
"[Blue] The Snake (zzzZZZzzzZZZ),\n"
"[Blue] what Snake (zzzZZZzzzZZZ) (not beautiful),\n"
"[Blue] it's a Snake (zzzZZZzzzZZZ) (unusual),\n"
"Panda (It's so cute)\n"
"The Panda (It's so cute),\n"
"what Panda (It's so cute) (not necessary),\n"
"it's a Panda (It's so cute) (unusual),\n"
"Leopard (the big one)\n"
"The Leopard (the big one),\n"
"what Leopard (the big one) (not usual),\n"
"it's a Leopard (the big one) (unusual),\n"
"Dragon (Fire? It's hot!)\n"
"The Dragon (Fire? It's hot!),\n"
"what Dragon (Fire? It's hot!) (not necessary),\n"
"it's a Dragon (Fire? It's hot!) (unusual),\n"
"Snake (zzzZZZzzzZZZ)\n"
"The Snake (zzzZZZzzzZZZ),\n"
"what Snake (zzzZZZzzzZZZ) (not beautiful),\n"
"it's a Snake (zzzZZZzzzZZZ) (unusual),\n"
"Panda\n"
"The Panda,\n"
"what Panda (not necessary),\n"
"it's a Panda (unusual),\n"
"Leopard\n"
"The Leopard,\n"
"what Leopard (not needed),\n"
"it's a Leopard (unusual),\n"
"Dragon\n"
"The Dragon,\n"
"what Dragon (not usual),\n"
"it's a Dragon (unusual),\n"
"Snake \n"
"The Snake ,\n"
"what Snake (not beautiful),\n"
"it's a Snake (unusual),")
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