Fixed bug #470582, using a modified version of patch #527371,
from Greg Chapman.

* Modules/_sre.c
  (lastmark_restore): New function, implementing algorithm to restore
  a state to a given lastmark. In addition to the similar algorithm used
  in a few places of SRE_MATCH, restore lastindex when restoring lastmark.
  (SRE_MATCH): Replace lastmark inline restoring by lastmark_restore(),
  function. Also include it where missing. In SRE_OP_MARK, set lastindex
  only if i > lastmark.

* Lib/test/re_tests.py
* Lib/test/test_sre.py
  Included regression tests for the fixed bugs.

* Misc/NEWS
  Mention fixes.
diff --git a/Lib/test/re_tests.py b/Lib/test/re_tests.py
index 953e4fd..d6f04f0 100755
--- a/Lib/test/re_tests.py
+++ b/Lib/test/re_tests.py
@@ -646,6 +646,8 @@
     (r'a[^>]*?b', 'a>b', FAIL),
     # bug 490573: minimizing repeat problem
     (r'^a*?$', 'foo', FAIL),
+    # bug 470582: nested groups problem
+    (r'^((a)c)?(ab)$', 'ab', SUCCEED, 'g1+"-"+g2+"-"+g3', 'None-None-ab'),
 ]
 
 try: