---
slug: "replace-version-number-pattern-python"
title: "Replacing Version Numbers with Python re (Regex Replacement Only Within Parentheses)"
description: "Use a lambda callback with Python's `re.sub` to replace only a captured group (e.g. a version number) inside a larger pattern."
url: "https://www.ytyng.com/en/blog/replace-version-number-pattern-python"
publish_date: "2018-09-21T03:37:25Z"
created: "2018-09-21T03:37:25Z"
updated: "2026-05-11T13:11:43.202Z"
categories: []
keywords: ""
featured_image_url: "https://media.ytyng.com/resize/20230812/7c9a39df15584857980f3e6f95ecac5b.png.webp?width=768"
has_video: false
has_music: false
video_urls: []
music_urls: []
lang: "en"
---

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

<p>The file looks like</p>
<p>version_number = "19";</p>
<p>and when you want to replace that file using a regular expression,</p>
<pre style="background-color: #ffffff; color: #000000; font-family: 'Menlo'; font-size: 9.0pt;"><span style="color: #008080; font-weight: bold;">version_number = "(\d+)";</span></pre>
<p>you want to use only the version number as the regular expression pattern without enclosing the other parts in pattern symbols.</p>
<p>However, after replacing, you want to obtain a string that includes version_number, such as</p>
<p>version_number = "20";</p>
<pre style="background-color: #ffffff; color: #000000; font-family: 'Menlo'; font-size: 9.0pt;">regex = re.compile(<span style="color: #008000; font-weight: bold;">'version_number = "(\d+)";'</span>)<span style="color: #000080; font-weight: bold;"><br /><br />def </span>_replace(match):<br />    startindex = match.regs[<span style="color: #0000ff;">1</span>][<span style="color: #0000ff;">0</span>] - match.regs[<span style="color: #0000ff;">0</span>][<span style="color: #0000ff;">0</span>]<br />    end_index = match.regs[<span style="color: #0000ff;">0</span>][<span style="color: #0000ff;">1</span>] - match.regs[<span style="color: #0000ff;">1</span>][<span style="color: #0000ff;">1</span>]<br />    <span style="color: #000080; font-weight: bold;">return </span>match.group(<span style="color: #0000ff;">0</span>)[:startindex] + <span style="color: #000080;">str</span>(value) + match.group(<span style="color: #0000ff;">0</span>)[-end_index:]<br /><span style="color: #000080; font-weight: bold;">return </span><span style="color: #94558d;"></span>regex.sub(_replace, <span style="color: #94558d;">self</span>.get_source_code())</pre>
<p>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.</p>
