Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 26dfaac

Browse files
committed
#17341: Include name in re error message about invalid group name.
Patch by Jason Michalski.
1 parent f2fa5fc commit 26dfaac

4 files changed

Lines changed: 18 additions & 2 deletions

File tree

Lib/sre_parse.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -600,7 +600,7 @@ def _parse(source, state):
600600
if not name:
601601
raise error("missing group name")
602602
if not name.isidentifier():
603-
raise error("bad character in group name")
603+
raise error("bad character in group name %r" % name)
604604
elif sourcematch("="):
605605
# named backreference
606606
name = ""
@@ -614,7 +614,8 @@ def _parse(source, state):
614614
if not name:
615615
raise error("missing group name")
616616
if not name.isidentifier():
617-
raise error("bad character in group name")
617+
raise error("bad character in backref group name "
618+
"%r" % name)
618619
gid = state.groupdict.get(name)
619620
if gid is None:
620621
raise error("unknown group name")

Lib/test/test_re.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import io
44
import re
55
from re import Scanner
6+
import sre_constants
67
import sys
78
import string
89
import traceback
@@ -1029,6 +1030,16 @@ def test_repeat_minmax_overflow_maxrepeat(self):
10291030
self.assertRaises(OverflowError, re.compile, r".{,%d}" % MAXREPEAT)
10301031
self.assertRaises(OverflowError, re.compile, r".{%d,}?" % MAXREPEAT)
10311032

1033+
def test_backref_group_name_in_exception(self):
1034+
# Issue 17341: Poor error message when compiling invalid regex
1035+
with self.assertRaisesRegex(sre_constants.error, '<foo>'):
1036+
re.compile('(?P=<foo>)')
1037+
1038+
def test_group_name_in_exception(self):
1039+
# Issue 17341: Poor error message when compiling invalid regex
1040+
with self.assertRaisesRegex(sre_constants.error, '\?foo'):
1041+
re.compile('(?P<?foo>)')
1042+
10321043

10331044
def run_re_tests():
10341045
from test.re_tests import tests, SUCCEED, FAIL, SYNTAX_ERROR

Misc/ACKS

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -805,6 +805,7 @@ Piotr Meyer
805805
Alexis Métaireau
806806
Steven Miale
807807
Trent Mick
808+
Jason Michalski
808809
Franck Michea
809810
Tom Middleton
810811
Stan Mihai

Misc/NEWS

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,9 @@ Core and Builtins
2929
Library
3030
-------
3131

32+
- Issue #17341: Include the invalid name in the error messages from re about
33+
invalid group names.
34+
3235
- Issue #17702: os.environ now raises KeyError with the original environment
3336
variable name (str on UNIX), instead of using the encoded name (bytes on
3437
UNIX).

0 commit comments

Comments
 (0)