# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"\((?:[^()]++|(?R))*\)"
test_str = ("SELECT Name AS [Object Name], Switch([Type]=5,'Query',[Type]=-32768,'Form',[Type]=6,'Table') AS [Object Type], Switch([Type]=5,1,[Type]=-32768,2,[Type] In (1,4,6),6) AS [Object Type ID], Left(Name,4) as Prefix, LTrim(RTrim(Mid([Name],5,30))) as Suffix\n\n"
"SELECT \"Amy's code is righteous.\", left(\"abc\",1), right('source code',4), \"Bill's code has been righteous too.\"\n\n"
"----------\n\n"
"End goal is to replace all commas in SQL SELECT clause with comma+linefeed but ignore commas inside parenthesis (which may be nested).\n\n"
"\\((?:[^()]++|(?R))*\\)\n\n"
"This expression will find all of the nested parentheis using recursion. I want to do one of these two options:\n"
" a) Replace all commas in the matched groups with the pipe \"|\" character, \n"
" then with two simple StrReplace() calls: replace all commas with comma+linefeed, then replace all | with comma.\n"
"OR\n"
" b) Select all text that is not in the matched group and replace commas with comma+linefeed.\n\n"
"I'm using AutoHotkey and the RegExReplace() function.")
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