mirror of
https://github.com/python/cpython.git
synced 2025-08-30 05:35:08 +00:00
Issue 24454: Improve the usability of the re match object named group API
This commit is contained in:
parent
a3c1728bb6
commit
605bdae078
4 changed files with 82 additions and 1 deletions
|
@ -441,6 +441,50 @@ class ReTests(unittest.TestCase):
|
|||
self.assertEqual(m.group(2, 1), ('b', 'a'))
|
||||
self.assertEqual(m.group(Index(2), Index(1)), ('b', 'a'))
|
||||
|
||||
def test_match_getitem(self):
|
||||
pat = re.compile('(?:(?P<a1>a)|(?P<b2>b))(?P<c3>c)?')
|
||||
|
||||
m = pat.match('a')
|
||||
self.assertEqual(m['a1'], 'a')
|
||||
self.assertEqual(m['b2'], None)
|
||||
self.assertEqual(m['c3'], None)
|
||||
self.assertEqual('a1={a1} b2={b2} c3={c3}'.format_map(m), 'a1=a b2=None c3=None')
|
||||
self.assertEqual(m[0], 'a')
|
||||
self.assertEqual(m[1], 'a')
|
||||
self.assertEqual(m[2], None)
|
||||
self.assertEqual(m[3], None)
|
||||
with self.assertRaisesRegex(IndexError, 'no such group'):
|
||||
m['X']
|
||||
with self.assertRaisesRegex(IndexError, 'no such group'):
|
||||
m[-1]
|
||||
with self.assertRaisesRegex(IndexError, 'no such group'):
|
||||
m[4]
|
||||
with self.assertRaisesRegex(IndexError, 'no such group'):
|
||||
m[0, 1]
|
||||
with self.assertRaisesRegex(IndexError, 'no such group'):
|
||||
m[(0,)]
|
||||
with self.assertRaisesRegex(IndexError, 'no such group'):
|
||||
m[(0, 1)]
|
||||
with self.assertRaisesRegex(KeyError, 'a2'):
|
||||
'a1={a2}'.format_map(m)
|
||||
|
||||
m = pat.match('ac')
|
||||
self.assertEqual(m['a1'], 'a')
|
||||
self.assertEqual(m['b2'], None)
|
||||
self.assertEqual(m['c3'], 'c')
|
||||
self.assertEqual('a1={a1} b2={b2} c3={c3}'.format_map(m), 'a1=a b2=None c3=c')
|
||||
self.assertEqual(m[0], 'ac')
|
||||
self.assertEqual(m[1], 'a')
|
||||
self.assertEqual(m[2], None)
|
||||
self.assertEqual(m[3], 'c')
|
||||
|
||||
# Cannot assign.
|
||||
with self.assertRaises(TypeError):
|
||||
m[0] = 1
|
||||
|
||||
# No len().
|
||||
self.assertRaises(TypeError, len, m)
|
||||
|
||||
def test_re_fullmatch(self):
|
||||
# Issue 16203: Proposal: add re.fullmatch() method.
|
||||
self.assertEqual(re.fullmatch(r"a", "a").span(), (0, 1))
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue