@@ -336,26 +336,26 @@ def group(match_result, group_nr, string):
336
336
while pos != - 1 and start < n :
337
337
if pos + 1 < n :
338
338
if repl [pos + 1 ].isdigit () and match_result .groupCount > 0 :
339
+ # TODO: Should handle backreferences longer than 1 digit and fall back to octal escapes.
339
340
group_nr = int (repl [pos + 1 ].decode ('ascii' )) if self .__binary else int (repl [pos + 1 ])
340
341
group_str = group (match_result , group_nr , string )
341
342
if group_str is None :
342
- raise ValueError ("invalid group reference %s at position %s" % (group_nr , pos ))
343
+ raise error ("invalid group reference %s at position %s" % (group_nr , pos ))
343
344
result += repl [start :pos ] + group_str
344
345
start = pos + 2
345
346
elif repl [pos + 1 ] == (b'g' if self .__binary else 'g' ):
346
347
group_ref , group_ref_end , digits_only = self .__extract_groupname (repl , pos + 2 )
347
348
if group_ref :
348
349
group_str = group (match_result , int (group_ref ) if digits_only else pattern .groups [group_ref ], string )
349
350
if group_str is None :
350
- raise ValueError ("invalid group reference %s at position %s" % (group_ref , pos ))
351
+ raise error ("invalid group reference %s at position %s" % (group_ref , pos ))
351
352
result += repl [start :pos ] + group_str
352
353
start = group_ref_end + 1
353
354
elif repl [pos + 1 ] == backslash :
354
355
result += repl [start :pos ] + backslash
355
356
start = pos + 2
356
357
else :
357
- result += repl [start :pos + 2 ]
358
- start = pos + 2
358
+ assert False , "unexpected escape in re.sub"
359
359
pos = repl .find (backslash , start )
360
360
result += repl [start :]
361
361
return result
@@ -386,7 +386,10 @@ def sub(self, repl, string, count=0):
386
386
is_string_rep = isinstance (repl , str ) or _is_bytes_like (repl )
387
387
if is_string_rep :
388
388
self .__check_input_type (repl )
389
- repl = _process_escape_sequences (repl )
389
+ try :
390
+ repl = _process_escape_sequences (repl )
391
+ except ValueError as e :
392
+ raise error (str (e ))
390
393
while (count == 0 or n < count ) and pos <= len (string ):
391
394
match_result = tregex_call_exec (pattern .exec , string , pos )
392
395
if not match_result .isMatch :
0 commit comments