# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"\(\s*define\s*(\(.*?\))"
test_str = ("#lang sicp\n"
"(define (square x) (* x x))\n"
"(define (average x y) (/ (+ x y) 2))\n\n\n"
"; using block scope\n"
"(define (sqrt x)\n"
" ; x is always the same -- \"4\" or whatever we pass to it, so we don't need that\n"
" ; in every single function that we define, we can just inherit it from above.\n"
" (define (improve guess) (average guess (/ x guess)))\n"
" (define (good-enough? guess) (< (abs (- (square guess) x)) 0.001 ))\n"
" (define (sqrt-iter guess) (if (good-enough? guess) guess (sqrt-iter (improve guess))))\n"
" (sqrt-iter 1.0)\n"
")\n"
"(sqrt 4)\n\n"
"(define (inc x) (+ x 1))\n"
"(define (dec x) (- x 1))\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