Skip to content

Commit

Permalink
Don't include unnamed groups in groupdict (#1524)
Browse files Browse the repository at this point in the history
  • Loading branch information
slozier authored Aug 2, 2022
1 parent 9292a33 commit e631b42
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 9 deletions.
20 changes: 11 additions & 9 deletions Src/IronPython.Modules/re.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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))]
Expand Down
6 changes: 6 additions & 0 deletions Tests/modules/io_related/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -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<foo>.*)(.*)', 'bar').groupdict()
self.assertEqual(d, {'foo': 'bar'})

run_test(__name__)

0 comments on commit e631b42

Please sign in to comment.