Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 44 additions & 1 deletion src/core/IronPython.Modules/re.cs
Original file line number Diff line number Diff line change
Expand Up @@ -912,6 +912,49 @@ private static RegexOptions FlagsToOption(ReFlags flags) {
return opts;
}

/// <summary>
/// Escapes the '[' characters that are literals inside a character class.
/// .NET reads "-[" inside a character class as the start of a class subtraction.
/// </summary>
private static string EscapeBracketsInCharacterClasses(string pattern) {
StringBuilder? sb = null;
int copied = 0; // pattern up to this index has been copied to sb
bool isCharClass = false;

for (int i = 0; i < pattern.Length; i++) {
switch (pattern[i]) {
case '\\':
i++; // skip the escaped character
break;
case '[':
if (isCharClass) {
sb ??= new StringBuilder(pattern.Length + 4);
sb.Append(pattern, copied, i - copied).Append('\\');
copied = i;
} else {
isCharClass = true;
if (i + 1 < pattern.Length && pattern[i + 1] == '^') i++;
if (i + 1 < pattern.Length && pattern[i + 1] == ']') i++; // a leading ] is a literal
}
break;
case ']':
isCharClass = false;
break;
case '(':
// the content of a comment is not part of the expression
if (!isCharClass && string.CompareOrdinal(pattern, i, "(?#", 0, 3) == 0) {
int end = pattern.IndexOf(')', i);
if (end >= 0) i = end;
}
break;
}
}

if (sb is null) return pattern;
sb.Append(pattern, copied, pattern.Length - copied);
return sb.ToString();
}

private static readonly char[] _endOfLineChars = new[] { '\r', '\n' };
private static readonly char[] _preParsedChars = new[] { '(', '{', '[', ']' };
private const string _mangledNamedGroup = "___PyRegexNameMangled";
Expand Down Expand Up @@ -1193,7 +1236,7 @@ static string ApplyVerbose(string pattern) {
}
}

return pattern;
return EscapeBracketsInCharacterClasses(pattern);

bool MaybeParseFlags(ReadOnlySpan<char> pattern, out int consumed, out ReFlags flags) {
consumed = default;
Expand Down
16 changes: 16 additions & 0 deletions tests/suite/modules/io_related/test_re.py
Original file line number Diff line number Diff line change
Expand Up @@ -876,6 +876,22 @@ def test_range_starting_with_escaped_hyphen(self):
self.assertEqual(re.match(r'(?i)[\--/]{2}', './').group(), './')
self.assertEqual(re.findall(r'x[\--/]y|[\--/]z', 'x.y-z'), ['x.y', '-z'])

def test_bracket_in_character_class(self):
# '[' is a literal inside a character class, also after '-' (.NET reads '-[' as a class subtraction)
self.assertEqual(re.findall(r'[+-[]', '*+Z[]'), ['+', 'Z', '['])
self.assertEqual(re.findall(r'[-[]', 'a-[b'), ['-', '['])
self.assertEqual(re.findall(r'[a-z-[]', '-[A'), ['-', '['])
self.assertEqual(re.findall(r'[^+-[]', '*+Z[]'), ['*', ']'])
self.assertEqual(re.findall(r'[a\-[b]]', 'a-[b]'), ['b]'])
self.assertEqual(re.findall(r'[]+-[]', ']+Z[ '), [']', '+', 'Z', '['])
self.assertEqual(re.findall(r'[[a]', '[a]'), ['[', 'a'])
self.assertEqual(re.findall(r'\[a-[b]', '[a-[b'), []) # an escaped [ does not start a class
self.assertEqual(re.findall(r'(?#[)[+-[]', 'Z)'), ['Z']) # nor does one in a comment
self.assertEqual(re.findall(r'(?x) [-[] # [', 'a-[ '), ['-', '['])
self.assertTrue(re.match(r'[+-[]', 'Z', re.ASCII))
self.assertTrue(re.match(br'[+-[]', b'Z'))
self.assertRaises(re.error, re.compile, r'[x-[]') # reversed range

def test_mixed_named_and_unnamed_groups(self):
example1=r"(?P<one>Blah)"
example2=r"(?P<one>(Blah))"
Expand Down
Loading