From 5f72f7a79f79b3c0caf5b88ab9ed7f2aa2ebd225 Mon Sep 17 00:00:00 2001 From: Jonathan Eunice Date: Sat, 17 Jun 2017 03:28:17 -0400 Subject: [PATCH 1/6] added \N{name} escapes to re patterns --- Doc/library/re.rst | 5 ++++- Lib/sre_parse.py | 28 ++++++++++++++++++++++++++++ Lib/test/test_re.py | 33 +++++++++++++++++++++++++++++++++ 3 files changed, 65 insertions(+), 1 deletion(-) diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 0b9d9755f30ec6..6a0bbd328541d4 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -443,7 +443,7 @@ character ``'$'``. Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser:: - \a \b \f \n + \a \b \f \n \N{name} \r \t \u \U \v \x \\ @@ -464,6 +464,9 @@ three digits in length. .. versionchanged:: 3.6 Unknown escapes consisting of ``'\'`` and an ASCII letter now are errors. +.. versionchanged:: 3.7 + The ``'\N{name}'`` escape sequence has been added. As in string literals, + it expands to the named Unicode character (e.g. ``'\N{EM DASH}'``). .. seealso:: diff --git a/Lib/sre_parse.py b/Lib/sre_parse.py index 545252074f63d1..a6f726aef9b28d 100644 --- a/Lib/sre_parse.py +++ b/Lib/sre_parse.py @@ -13,6 +13,7 @@ # XXX: show string offset and offending character for all errors from sre_constants import * +from ast import literal_eval SPECIAL_CHARS = ".\\[{()*+?^$|" REPEAT_CHARS = "*+?{" @@ -25,6 +26,11 @@ WHITESPACE = frozenset(" \t\n\r\v\f") +UNICODE_NAME = ASCIILETTERS | DIGITS | frozenset(' -') +CLOSING_BRACE = frozenset("}") +OPENING_BRACE = frozenset("{") + + _REPEATCODES = frozenset({MIN_REPEAT, MAX_REPEAT}) _UNITCODES = frozenset({ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY}) @@ -322,6 +328,17 @@ def _class_escape(source, escape): c = int(escape[2:], 16) chr(c) # raise ValueError for invalid code return LITERAL, c + elif c == "N" and source.istext: + # named unicode escape e.g. \N{EM DASH} + escape += source.getwhile(1, OPENING_BRACE) + escape += source.getwhile(100, UNICODE_NAME) + escape += source.getwhile(1, CLOSING_BRACE) + try: + c = ord(literal_eval('"%s"' % escape)) + except SyntaxError: + charname = escape[2:].strip('{}') + raise source.error("unknown Unicode character name %s" % charname, len(escape)) + return LITERAL, c elif c in OCTDIGITS: # octal escape (up to three digits) escape += source.getwhile(2, OCTDIGITS) @@ -370,6 +387,17 @@ def _escape(source, escape, state): c = int(escape[2:], 16) chr(c) # raise ValueError for invalid code return LITERAL, c + elif c == "N" and source.istext: + # named unicode escape e.g. \N{EM DASH} + escape += source.getwhile(1, OPENING_BRACE) + escape += source.getwhile(100, UNICODE_NAME) + escape += source.getwhile(1, CLOSING_BRACE) + try: + c = ord(literal_eval('"%s"' % escape)) + except SyntaxError: + charname = escape[2:].strip('{}') + raise source.error("unknown Unicode character name %s" % charname, len(escape)) + return LITERAL, c elif c == "0": # octal escape escape += source.getwhile(2, OCTDIGITS) diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 0ea5a20469646b..a05c35a2a4740e 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -700,6 +700,39 @@ def test_other_escapes(self): with self.subTest(c): self.assertRaises(re.error, re.compile, '[\\%c]' % c) + def test_named_unicode_escapes(self): + # test individual Unicode named escapes + suites = [ + [ # basic matches + ['\u2014', r'\u2014', '\N{EM DASH}', + r'\N{EM DASH}'], # pattern + ['\u2014', '\N{EM DASH}', '—', '—and more'], # matches + ['\u2015', '\N{EN DASH}'] # no match + ], + [ # character set matches + ['[\u2014-\u2020]', r'[\u2014-\u2020]', + '[\N{EM DASH}-\N{DAGGER}]', r'[\N{EM DASH}-\N{DAGGER}]', + '[\u2014-\N{DAGGER}]', '[\N{EM DASH}-\u2020]',], # pattern + ['\u2014', '\N{EM DASH}', '—', '—and more', '\u2020', + '\N{DAGGER}', '†', '\u2017', '\N{DOUBLE LOW LINE}'], + ['\u2011', '\N{EN DASH}', '\u2013', 'xyz', '\u2021'] + ], + ] + + for patterns, match_yes, match_no in suites: + for pat in patterns: + for target in match_yes: + self.assertTrue(re.match(pat, target)) + for target in match_no: + self.assertIsNone(re.match(pat, target)) + + # test errors in \N{name} handling - only valid names should pass + badly_formed = [r'\N{BUBBA DASH}', r'\N{EM DASH', + r'\NEM DASH}', r'\NOGGIN'] + for bad in badly_formed: + with self.assertRaises(re.error): + re.compile(bad) + def test_string_boundaries(self): # See http://bugs.python.org/issue10713 self.assertEqual(re.search(r"\b(abc)\b", "abc").group(1), From 7fb2983532cd951bc3ecd041ad806b4c1c10d1aa Mon Sep 17 00:00:00 2001 From: Jonathan Eunice Date: Sat, 17 Jun 2017 12:08:29 -0400 Subject: [PATCH 2/6] mention limitation of \N sequences to Unicode patterns --- Doc/library/re.rst | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 6a0bbd328541d4..94a6acffc92d73 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -450,7 +450,7 @@ accepted by the regular expression parser:: (Note that ``\b`` is used to represent word boundaries, and means "backspace" only inside character classes.) -``'\u'`` and ``'\U'`` escape sequences are only recognized in Unicode +``'\u'``, ``'\U'``, and ``'\N{name}'`` escape sequences are only recognized in Unicode patterns. In bytes patterns they are not treated specially. Octal escapes are included in a limited form. If the first digit is a 0, or if From 4db797b1cfe06c265e56e40d63501bc76e616c0f Mon Sep 17 00:00:00 2001 From: Jonathan Eunice Date: Sat, 17 Jun 2017 12:10:29 -0400 Subject: [PATCH 3/6] mention \N escapes more tersely --- Doc/library/re.rst | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/Doc/library/re.rst b/Doc/library/re.rst index 94a6acffc92d73..9fafc0f462d599 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -443,14 +443,14 @@ character ``'$'``. Most of the standard escapes supported by Python string literals are also accepted by the regular expression parser:: - \a \b \f \n \N{name} + \a \b \f \n \N \r \t \u \U \v \x \\ (Note that ``\b`` is used to represent word boundaries, and means "backspace" only inside character classes.) -``'\u'``, ``'\U'``, and ``'\N{name}'`` escape sequences are only recognized in Unicode +``'\u'``, ``'\U'``, and ``'\N'`` escape sequences are only recognized in Unicode patterns. In bytes patterns they are not treated specially. Octal escapes are included in a limited form. If the first digit is a 0, or if From 2272cec13b53c405d86c45d404f035f201c0baef Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Thu, 8 Feb 2018 18:51:45 +0200 Subject: [PATCH 4/6] Use unicodedata instead of eval. --- Lib/sre_parse.py | 48 ++++++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/Lib/sre_parse.py b/Lib/sre_parse.py index e7c76c2f493550..2dd9c8016897dc 100644 --- a/Lib/sre_parse.py +++ b/Lib/sre_parse.py @@ -13,7 +13,7 @@ # XXX: show string offset and offending character for all errors from sre_constants import * -from ast import literal_eval +import unicodedata SPECIAL_CHARS = ".\\[{()*+?^$|" REPEAT_CHARS = "*+?{" @@ -26,10 +26,6 @@ WHITESPACE = frozenset(" \t\n\r\v\f") -UNICODE_NAME = ASCIILETTERS | DIGITS | frozenset(' -') -CLOSING_BRACE = frozenset("}") -OPENING_BRACE = frozenset("{") - _REPEATCODES = frozenset({MIN_REPEAT, MAX_REPEAT}) _UNITCODES = frozenset({ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY}) @@ -270,19 +266,19 @@ def getwhile(self, n, charset): result += c self.__next() return result - def getuntil(self, terminator): + def getuntil(self, terminator, name): result = '' while True: c = self.next self.__next() if c is None: if not result: - raise self.error("missing group name") + raise self.error("missing " + name) raise self.error("missing %s, unterminated name" % terminator, len(result)) if c == terminator: if not result: - raise self.error("missing group name", 1) + raise self.error("missing " + name, 1) break result += c return result @@ -330,14 +326,14 @@ def _class_escape(source, escape): return LITERAL, c elif c == "N" and source.istext: # named unicode escape e.g. \N{EM DASH} - escape += source.getwhile(1, OPENING_BRACE) - escape += source.getwhile(100, UNICODE_NAME) - escape += source.getwhile(1, CLOSING_BRACE) + if not source.match('{'): + raise source.error("missing {") + charname = source.getuntil('}', 'character name') try: - c = ord(literal_eval('"%s"' % escape)) - except SyntaxError: - charname = escape[2:].strip('{}') - raise source.error("unknown Unicode character name %s" % charname, len(escape)) + c = ord(unicodedata.lookup(charname)) + except KeyError: + raise source.error("undefined character name %r" % charname, + len(charname) + len(r'\N{}')) return LITERAL, c elif c in OCTDIGITS: # octal escape (up to three digits) @@ -389,14 +385,14 @@ def _escape(source, escape, state): return LITERAL, c elif c == "N" and source.istext: # named unicode escape e.g. \N{EM DASH} - escape += source.getwhile(1, OPENING_BRACE) - escape += source.getwhile(100, UNICODE_NAME) - escape += source.getwhile(1, CLOSING_BRACE) + if not source.match('{'): + raise source.error("missing {") + charname = source.getuntil('}', 'character name') try: - c = ord(literal_eval('"%s"' % escape)) - except SyntaxError: - charname = escape[2:].strip('{}') - raise source.error("unknown Unicode character name %s" % charname, len(escape)) + c = ord(unicodedata.lookup(charname)) + except KeyError: + raise source.error("undefined character name %r" % charname, + len(charname) + len(r'\N{}')) return LITERAL, c elif c == "0": # octal escape @@ -707,13 +703,13 @@ def _parse(source, state, verbose, nested, first=False): # python extensions if sourcematch("<"): # named group: skip forward to end of name - name = source.getuntil(">") + name = source.getuntil(">", "group name") if not name.isidentifier(): msg = "bad character in group name %r" % name raise source.error(msg, len(name) + 1) elif sourcematch("="): # named backreference - name = source.getuntil(")") + name = source.getuntil(")", "group name") if not name.isidentifier(): msg = "bad character in group name %r" % name raise source.error(msg, len(name) + 1) @@ -776,7 +772,7 @@ def _parse(source, state, verbose, nested, first=False): elif char == "(": # conditional backreference group - condname = source.getuntil(")") + condname = source.getuntil(")", "group name") if condname.isidentifier(): condgroup = state.groupdict.get(condname) if condgroup is None: @@ -1005,7 +1001,7 @@ def addgroup(index, pos): name = "" if not s.match("<"): raise s.error("missing <") - name = s.getuntil(">") + name = s.getuntil(">", "group name") if name.isidentifier(): try: index = groupindex[name] From 463d667429f9d0cb5dc432aca5020d6610c0e5cb Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Thu, 8 Feb 2018 18:52:34 +0200 Subject: [PATCH 5/6] Make tests more explicit. Increase coverage. --- Lib/test/test_re.py | 59 ++++++++++++++++++++++++--------------------- 1 file changed, 31 insertions(+), 28 deletions(-) diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py index 7ee1b439831c17..ab1d985d59f878 100644 --- a/Lib/test/test_re.py +++ b/Lib/test/test_re.py @@ -696,36 +696,39 @@ def test_other_escapes(self): def test_named_unicode_escapes(self): # test individual Unicode named escapes - suites = [ - [ # basic matches - ['\u2014', r'\u2014', '\N{EM DASH}', - r'\N{EM DASH}'], # pattern - ['\u2014', '\N{EM DASH}', '—', '—and more'], # matches - ['\u2015', '\N{EN DASH}'] # no match - ], - [ # character set matches - ['[\u2014-\u2020]', r'[\u2014-\u2020]', - '[\N{EM DASH}-\N{DAGGER}]', r'[\N{EM DASH}-\N{DAGGER}]', - '[\u2014-\N{DAGGER}]', '[\N{EM DASH}-\u2020]',], # pattern - ['\u2014', '\N{EM DASH}', '—', '—and more', '\u2020', - '\N{DAGGER}', '†', '\u2017', '\N{DOUBLE LOW LINE}'], - ['\u2011', '\N{EN DASH}', '\u2013', 'xyz', '\u2021'] - ], - ] - - for patterns, match_yes, match_no in suites: - for pat in patterns: - for target in match_yes: - self.assertTrue(re.match(pat, target)) - for target in match_no: - self.assertIsNone(re.match(pat, target)) + self.assertTrue(re.match(r'\N{LESS-THAN SIGN}', '<')) + self.assertTrue(re.match(r'\N{less-than sign}', '<')) + self.assertIsNone(re.match(r'\N{LESS-THAN SIGN}', '>')) + self.assertTrue(re.match(r'\N{SNAKE}', '\U0001f40d')) + self.assertTrue(re.match(r'\N{ARABIC LIGATURE UIGHUR KIRGHIZ YEH WITH ' + r'HAMZA ABOVE WITH ALEF MAKSURA ISOLATED FORM}', + '\ufbf9')) + self.assertTrue(re.match(r'[\N{LESS-THAN SIGN}-\N{GREATER-THAN SIGN}]', + '=')) + self.assertIsNone(re.match(r'[\N{LESS-THAN SIGN}-\N{GREATER-THAN SIGN}]', + ';')) # test errors in \N{name} handling - only valid names should pass - badly_formed = [r'\N{BUBBA DASH}', r'\N{EM DASH', - r'\NEM DASH}', r'\NOGGIN'] - for bad in badly_formed: - with self.assertRaises(re.error): - re.compile(bad) + self.checkPatternError(r'\N', 'missing {', 2) + self.checkPatternError(r'[\N]', 'missing {', 3) + self.checkPatternError(r'\N{', 'missing character name', 3) + self.checkPatternError(r'[\N{', 'missing character name', 4) + self.checkPatternError(r'\N{}', 'missing character name', 3) + self.checkPatternError(r'[\N{}]', 'missing character name', 4) + self.checkPatternError(r'\NSNAKE}', 'missing {', 2) + self.checkPatternError(r'[\NSNAKE}]', 'missing {', 3) + self.checkPatternError(r'\N{SNAKE', + 'missing }, unterminated name', 3) + self.checkPatternError(r'[\N{SNAKE]', + 'missing }, unterminated name', 4) + self.checkPatternError(r'[\N{SNAKE]}', + "undefined character name 'SNAKE]'", 1) + self.checkPatternError(r'\N{SPAM}', + "undefined character name 'SPAM'", 0) + self.checkPatternError(r'[\N{SPAM}]', + "undefined character name 'SPAM'", 1) + self.checkPatternError(br'\N{LESS-THAN SIGN}', r'bad escape \N', 0) + self.checkPatternError(br'[\N{LESS-THAN SIGN}]', r'bad escape \N', 1) def test_string_boundaries(self): # See http://bugs.python.org/issue10713 From 663c505b6f20cb9e709cf013ad94c7a7fc382881 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Thu, 8 Feb 2018 19:04:51 +0200 Subject: [PATCH 6/6] Update the documentation. --- Doc/library/re.rst | 2 +- Doc/whatsnew/3.8.rst | 2 ++ Lib/sre_parse.py | 1 - Misc/ACKS | 1 + .../next/Library/2018-02-08-18-59-11.bpo-30688.zBh4TH.rst | 2 ++ 5 files changed, 6 insertions(+), 2 deletions(-) create mode 100644 Misc/NEWS.d/next/Library/2018-02-08-18-59-11.bpo-30688.zBh4TH.rst diff --git a/Doc/library/re.rst b/Doc/library/re.rst index a15f00b7585051..475a8d285550f2 100644 --- a/Doc/library/re.rst +++ b/Doc/library/re.rst @@ -488,7 +488,7 @@ three digits in length. .. versionchanged:: 3.6 Unknown escapes consisting of ``'\'`` and an ASCII letter now are errors. -.. versionchanged:: 3.7 +.. versionchanged:: 3.8 The ``'\N{name}'`` escape sequence has been added. As in string literals, it expands to the named Unicode character (e.g. ``'\N{EM DASH}'``). diff --git a/Doc/whatsnew/3.8.rst b/Doc/whatsnew/3.8.rst index 60f54a0561e54e..41819815e39943 100644 --- a/Doc/whatsnew/3.8.rst +++ b/Doc/whatsnew/3.8.rst @@ -75,6 +75,8 @@ New Features Other Language Changes ====================== +* Added support of ``\N{name}`` escapes in :mod:`regular expressions `. + (Contributed by Jonathan Eunice and Serhiy Storchaka in :issue:`30688`.) New Modules diff --git a/Lib/sre_parse.py b/Lib/sre_parse.py index 2dd9c8016897dc..db01e844b43249 100644 --- a/Lib/sre_parse.py +++ b/Lib/sre_parse.py @@ -26,7 +26,6 @@ WHITESPACE = frozenset(" \t\n\r\v\f") - _REPEATCODES = frozenset({MIN_REPEAT, MAX_REPEAT}) _UNITCODES = frozenset({ANY, RANGE, IN, LITERAL, NOT_LITERAL, CATEGORY}) diff --git a/Misc/ACKS b/Misc/ACKS index c5eadc5ba0177c..3e413c1f8fdbbd 100644 --- a/Misc/ACKS +++ b/Misc/ACKS @@ -440,6 +440,7 @@ Andy Eskilsson André Espaze Stefan Esser Nicolas Estibals +Jonathan Eunice Carey Evans Stephen D Evans Tim Everett diff --git a/Misc/NEWS.d/next/Library/2018-02-08-18-59-11.bpo-30688.zBh4TH.rst b/Misc/NEWS.d/next/Library/2018-02-08-18-59-11.bpo-30688.zBh4TH.rst new file mode 100644 index 00000000000000..7d31680d651a59 --- /dev/null +++ b/Misc/NEWS.d/next/Library/2018-02-08-18-59-11.bpo-30688.zBh4TH.rst @@ -0,0 +1,2 @@ +Added support of ``\N{name}`` escapes in regular expressions. Based on +patch by Jonathan Eunice.