diff --git a/Src/IronPython.Modules/re.cs b/Src/IronPython.Modules/re.cs index bbed406ab..8fd62eee0 100644 --- a/Src/IronPython.Modules/re.cs +++ b/Src/IronPython.Modules/re.cs @@ -748,23 +748,25 @@ static string ValidateString(object? str) { void AppendGroup(StringBuilder sb, int index) => sb.Append(_m.Groups[index].Value); } - private static bool IsGroupNumber(string name) { - foreach (char c in name) { - if (!char.IsNumber(c)) return false; - } - return true; - } - [return: DictionaryTypeInfo(typeof(string), typeof(object))] public PythonDictionary groupdict(object? @default = null) { string[] groupNames = this.re._re.GetGroupNames(); Debug.Assert(groupNames.Length == this._m.Groups.Count); PythonDictionary d = new PythonDictionary(); for (int i = 0; i < groupNames.Length; i++) { - if (IsGroupNumber(groupNames[i])) continue; // python doesn't report group numbers - d[groupNames[i]] = re.GetGroupValue(_m.Groups[i], @default); + var groupName = groupNames[i]; + if (IsGroupNumber(groupName)) continue; // python doesn't report group numbers + if (groupName.StartsWith(_mangledNamedGroup, StringComparison.Ordinal)) continue; // don't include unnamed groups + d[groupName] = re.GetGroupValue(_m.Groups[i], @default); } return d; + + static bool IsGroupNumber(string name) { + foreach (char c in name) { + if (!char.IsNumber(c)) return false; + } + return true; + } } [return: SequenceTypeInfo(typeof(int))] diff --git a/Tests/modules/io_related/test_re.py b/Tests/modules/io_related/test_re.py index ef1fb8738..72c1139e4 100644 --- a/Tests/modules/io_related/test_re.py +++ b/Tests/modules/io_related/test_re.py @@ -836,4 +836,10 @@ def test_pos_endpos(self): for m2 in (p.finditer("a", -100), p.finditer("a", -100, 100), p.finditer("a", endpos=100)): self.assertEqual(m.span(), next(m2).span()) + def test_ipy2_gh821(self): + # https://github.com/IronLanguages/ironpython2/issues/821 + # don't include unnamed groups in groupdict + d = re.match('(?P.*)(.*)', 'bar').groupdict() + self.assertEqual(d, {'foo': 'bar'}) + run_test(__name__)