-2

I have couple of files with like this, llm_rc_v3212.xml, llm_ds_v3232.xml. Names can be anything. however, common parameter would be_v3212. I want to match this number and replace it (ideally renaming the file).

How can i match this pattern with regex? I am trying to use re.sub, but not able to figure yet.

any help would be appreciated.

tgcloud
  • 857
  • 6
  • 18
  • 37

1 Answers1

1

Here is a working example. Take into account that depending on other filenames the regex might need to be changed.

import re

FILENAME_VERSION_REGEX = re.compile(r'_v(\d)+')


def rename(filename, replacement):
    full_replacement = r'_v{}'.format(replacement)
    new_filename = FILENAME_VERSION_REGEX.sub(full_replacement, filename)
    return new_filename

Tested with the filenames you gave:

>>> rename('llm_rc_v3212.xml', 1)
'llm_rc_v1.xml'

>>> rename('llm_ds_v3232.xml', 2)
'llm_ds_v2.xml'

>>> rename('llm_v232_uc.xml', 3)
'llm_v3_uc.xml'
Paco H.
  • 2,034
  • 7
  • 18