# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^\s*(enum[^{]*)\s*({)\s*([^}]+)\s*(};)"
test_str = ("#include <iostream>\n"
" \n"
"// enum that takes 16 bits\n"
"enum smallenum: int16_t\n"
"{\n"
" a,\n"
" b,\n"
" c\n"
"};\n"
" \n"
" \n"
"// color may be red (value 0), yellow (value 1), green (value 20), or blue (value 21)\n"
"enum color\n"
"{\n"
" red,\n"
" yellow,\n"
" green = 20,\n"
" blue\n"
"};\n"
" \n"
"// altitude may be altitude::high or altitude::low\n"
"enum class altitude: char\n"
"{ \n"
" high='h',\n"
" low='l', // C++11 allows the extra comma\n"
"}; \n"
" \n"
"// the constant d is 0, the constant e is 1, the constant f is 3\n"
"enum\n"
"{\n"
" d,\n"
" e,\n"
" f = e + 2\n"
"};\n"
" \n"
"//enumeration types (both scoped and unscoped) can have overloaded operators\n"
"std::ostream& operator<<(std::ostream& os, color c)\n"
"{\n"
" switch(c)\n"
" {\n"
" case red : os << \"red\"; break;\n"
" case yellow: os << \"yellow\"; break;\n"
" case green : os << \"green\"; break;\n"
" case blue : os << \"blue\"; break;\n"
" default : os.setstate(std::ios_base::failbit);\n"
" }\n"
" return os;\n"
"}\n"
" \n"
"std::ostream& operator<<(std::ostream& os, altitude al)\n"
"{\n"
" return os << static_cast<char>(al);\n"
"}\n"
" \n"
"int main()\n"
"{\n"
" color col = red;\n"
" altitude a;\n"
" a = altitude::low;\n"
" \n"
" std::cout << \"col = \" << col << '\\n'\n"
" << \"a = \" << a << '\\n'\n"
" << \"f = \" << f << '\\n';\n"
"}")
matches = re.finditer(regex, test_str, re.MULTILINE | re.DOTALL)
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