diff --git a/src/core/IronPython.Modules/re.cs b/src/core/IronPython.Modules/re.cs
index 393101b5d..cfc788ac8 100644
--- a/src/core/IronPython.Modules/re.cs
+++ b/src/core/IronPython.Modules/re.cs
@@ -912,6 +912,49 @@ private static RegexOptions FlagsToOption(ReFlags flags) {
return opts;
}
+ ///
+ /// Escapes the '[' characters that are literals inside a character class.
+ /// .NET reads "-[" inside a character class as the start of a class subtraction.
+ ///
+ 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";
@@ -1193,7 +1236,7 @@ static string ApplyVerbose(string pattern) {
}
}
- return pattern;
+ return EscapeBracketsInCharacterClasses(pattern);
bool MaybeParseFlags(ReadOnlySpan pattern, out int consumed, out ReFlags flags) {
consumed = default;
diff --git a/tests/suite/modules/io_related/test_re.py b/tests/suite/modules/io_related/test_re.py
index b6e2ad73f..5684a8c22 100644
--- a/tests/suite/modules/io_related/test_re.py
+++ b/tests/suite/modules/io_related/test_re.py
@@ -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"(?PBlah)"
example2=r"(?P(Blah))"