import re


def _replace_shard_suffix(filepath: str, replacement: str) -> str:
  """Replaces the shard suffix (must be at the end) with the given string."""
  (new_string, num_subs) = re.subn(
      pattern=r'^(.+?)-?\d{5,}(-of-\d{5,})?$',
      repl=rf'\g<1>{replacement}',
      string=filepath)
  if num_subs != 1:
    raise RuntimeError(
        f'Should do 1 shard suffix substitution, but did {num_subs}! '
        f'Filepath was {filepath}')
  return new_string