Skip to content

Commit e631b42

Browse files
authored
Don't include unnamed groups in groupdict (#1524)
1 parent 9292a33 commit e631b42

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

Src/IronPython.Modules/re.cs

Lines changed: 11 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -748,23 +748,25 @@ static string ValidateString(object? str) {
748748
void AppendGroup(StringBuilder sb, int index) => sb.Append(_m.Groups[index].Value);
749749
}
750750

751-
private static bool IsGroupNumber(string name) {
752-
foreach (char c in name) {
753-
if (!char.IsNumber(c)) return false;
754-
}
755-
return true;
756-
}
757-
758751
[return: DictionaryTypeInfo(typeof(string), typeof(object))]
759752
public PythonDictionary groupdict(object? @default = null) {
760753
string[] groupNames = this.re._re.GetGroupNames();
761754
Debug.Assert(groupNames.Length == this._m.Groups.Count);
762755
PythonDictionary d = new PythonDictionary();
763756
for (int i = 0; i < groupNames.Length; i++) {
764-
if (IsGroupNumber(groupNames[i])) continue; // python doesn't report group numbers
765-
d[groupNames[i]] = re.GetGroupValue(_m.Groups[i], @default);
757+
var groupName = groupNames[i];
758+
if (IsGroupNumber(groupName)) continue; // python doesn't report group numbers
759+
if (groupName.StartsWith(_mangledNamedGroup, StringComparison.Ordinal)) continue; // don't include unnamed groups
760+
d[groupName] = re.GetGroupValue(_m.Groups[i], @default);
766761
}
767762
return d;
763+
764+
static bool IsGroupNumber(string name) {
765+
foreach (char c in name) {
766+
if (!char.IsNumber(c)) return false;
767+
}
768+
return true;
769+
}
768770
}
769771

770772
[return: SequenceTypeInfo(typeof(int))]

Tests/modules/io_related/test_re.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -836,4 +836,10 @@ def test_pos_endpos(self):
836836
for m2 in (p.finditer("a", -100), p.finditer("a", -100, 100), p.finditer("a", endpos=100)):
837837
self.assertEqual(m.span(), next(m2).span())
838838

839+
def test_ipy2_gh821(self):
840+
# https://github.com/IronLanguages/ironpython2/issues/821
841+
# don't include unnamed groups in groupdict
842+
d = re.match('(?P<foo>.*)(.*)', 'bar').groupdict()
843+
self.assertEqual(d, {'foo': 'bar'})
844+
839845
run_test(__name__)

0 commit comments

Comments
 (0)