Replacing Version Numbers with Python re (Regex Replacement Only Within Parentheses)

2018-09-21 12:37 (6 years ago) ytyng

The file looks like

version_number = "19";

and when you want to replace that file using a regular expression,

version_number = "(\d+)";

you want to use only the version number as the regular expression pattern without enclosing the other parts in pattern symbols.

However, after replacing, you want to obtain a string that includes version_number, such as

version_number = "20";

regex = re.compile('version_number = "(\d+)";')

def
_replace(match):
startindex = match.regs[1][0] - match.regs[0][0]
end_index = match.regs[0][1] - match.regs[1][1]
return match.group(0)[:startindex] + str(value) + match.group(0)[-end_index:]
return regex.sub(_replace, self.get_source_code())

In this way, the match indices are stored in match.regs within the _replace callback, so by slicing the string with those indices, it might work well.

Currently unrated

Comments

Archive

2024
2023
2022
2021
2020
2019
2018
2017
2016
2015
2014
2013
2012
2011