You need to escape your backslash:

p.sub('gray \\1', s)

alternatively you can use a raw string as you already did for the regex:

p.sub(r'gray \1', s)
Answer from mac on Stack Overflow
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-regex-replace-captured-groups
Python Regex: Replace Captured Groups - GeeksforGeeks
July 23, 2025 - `flags`: Optional flags to modify the regex behavior. Python provides several ways to replace captured groups in a string: Example 1. Using re.sub() with Group References:
Discussions

Python how to replace content in the capture group of regex? - Stack Overflow
The documentation will tell you that you can use backreferences to substitute in the replacement string. ... Use a capturing group on the pattern you need to keep. More on stackoverflow.com
๐ŸŒ stackoverflow.com
May 24, 2017
regex - Replace named captured groups with arbitrary values in Python - Stack Overflow
I need to replace the value inside a capture group of a regular expression with some arbitrary value; I've had a look at the re.sub, but it seems to be working in a different way. I have a string ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
November 21, 2017
regex: Can I use numbered capture group references in strings outside of re.sub?
Do you have an example of the string you'd like to build? >>> match = re.search(pattern, str1) >>> match.groups() ('123', '456') >>> match.group(1) '123' You can also use [1] in recent versions. >>> match[1] '123' You could use f-strings >>> f'foo {match[1]} bar {match[2]}' 'foo 123 bar 456' Using m as the name would make it closer to \1 You could also use .format() and pass all the groups at once: >>> 'foo {} bar {}'.format(*match.groups()) 'foo 123 bar 456' >>> 'foo {1} bar {0}'.format(*match.groups()) 'foo 456 bar 123' More on reddit.com
๐ŸŒ r/learnpython
2
4
January 7, 2022
Python Regex instantly replace groups - Stack Overflow
Connect and share knowledge within a single location that is structured and easy to search. Learn more about Teams ... I want to build the new string instantaneously from the groups the Regex just captured. ... This is Python's regex substitution (replace) function. More on stackoverflow.com
๐ŸŒ stackoverflow.com
January 7, 2022
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ python regex replace with capture group
Python regex replace with capture group - Spark By {Examples}
May 31, 2024 - Regular expressions (regex) in Python provide a powerful way to manipulate and transform text. One useful feature is the ability to use capture groups in
๐ŸŒ
GitHub
gist.github.com โ€บ Integralist โ€บ 05247b9a12bad8a93c84c74e4784b8a7
[Python regex replace with capture group] #python #regex #replace #substring ยท GitHub
[Python regex replace with capture group] #python #regex #replace #substring - Python regex replace with capture group.py
๐ŸŒ
Regular-Expressions.info
regular-expressions.info โ€บ replacebackref.html
Reinserting Text Matched By Capturing Groups in The Replacement Text
In Python, if you have the regex (?P<name>group) then you can use its match in the replacement text with \g<name>. This syntax also works in the JGsoft applications and Delphi. Python and the JGsoft applications, but not Delphi, also support numbered backreferences using this syntax.
๐ŸŒ
Plain English
python.plainenglish.io โ€บ the-incredible-power-of-pythons-replace-regex-6cc217643f37
The incredible power of Pythonโ€™s replace regex | by Josh Weinstein | Python in Plain English
November 1, 2020 - In the first argument to the re.sub ... in the regex, of three, three, and four digits long, respectively. This pattern is designed to match 10 digit phone numbers which have no format thatโ€™s usually used in contact information or distinguishes the area code. The second argument, the replace string, is a template string which specifies the interpolation of the captured groups. In Pythonโ€™s regex, ...
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ regex โ€บ python regex replace pattern in a string using re.sub()
Python Regex Replace Pattern in a string using re.sub()
July 19, 2021 - import re # Original string ... replace two distinct patterns with two different replacements. ... So we will first capture two groups and then replace each group with a replacement function....
Find elsewhere
๐ŸŒ
Linux find Examples
queirozf.com โ€บ entries โ€บ python-regular-expressions-examples-reference
Python Regular Expressions: Examples & Reference
April 21, 2022 - import re # this pattern matches things like "foo-bar" or "bar-baz" pattern = "^(\w{3})-(\w{3})$" string1 = "abc-def" # returns Null if no match matches = re.match("^(\w{3})-(\w{3})$",string1) if matches: # match indices start at 1 first_group_match = matches.group(1) # abc second_group_match = matches.group(2) # def print(first_group_match+" AND "+second_group_match) # prints: "abc AND def" Only the first occurrence of the capture can be extracted.
๐ŸŒ
LearnByExample
learnbyexample.github.io โ€บ py_regular_expressions โ€บ groupings-and-backreferences.html
Groupings and backreferences - Understanding Python re(gex)?
One such is naming the capture groups and using that name for backreferencing instead of plain numbers. The syntax is (?P&LTname>pat) for naming the capture groups. The name used should be a valid Python identifier. Use 'name' for re.Match objects, \g&LTname> in replacement section and (?P=name) for backreferencing in RE definition.
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ how-to-use-python-regex-to-replace-using-captured-group
How to Use Python Regex to Replace Text with Captured Groups: A Step-by-Step Guide โ€” pythontutorials.net
One of the most versatile features of regex is **captured groups**โ€”subpatterns enclosed in parentheses that "capture" parts of a matched string. By combining captured groups with the `re.sub()` ...
๐ŸŒ
Python documentation
docs.python.org โ€บ 3 โ€บ howto โ€บ regex.html
Regular expression HOWTO โ€” Python 3.14.6 documentation
Except for the fact that you canโ€™t retrieve the contents of what the group matched, a non-capturing group behaves exactly the same as a capturing group; you can put anything inside it, repeat it with a repetition metacharacter such as *, and nest it within other groups (capturing or non-capturing).
๐ŸŒ
PYnative
pynative.com โ€บ home โ€บ python โ€บ regex โ€บ python regex capturing groups
Python Regex Capturing Groups โ€“ PYnative
April 12, 2021 - # Extract first group print(result.group(1)) # Extract second group print(result.group(2)) # Target string print(result.group(0))Code language: Python (python) So this is the simple way to access each of the groups as long as the patterns were matched. In earlier examples, we used the search method. It will return only the first match for each group. But what if a string contains the multiple occurrences of a regex group and you want to extract all matches. In this section, we will learn how to capture all matches to a regex group.
Top answer
1 of 5
9

This is a completely backwards use of regex. The point of capture groups is to hold text you want to keep, not text you want to replace.

Since you've written your regex the wrong way, you have to do most of the substitution operation manually:

"""
Replaces the text captured by named groups.
"""
def replace_groups(pattern, string, replacements):
    pattern = re.compile(pattern)
    # create a dict of {group_index: group_name} for use later
    groupnames = {index: name for name, index in pattern.groupindex.items()}

    def repl(match):
        # we have to split the matched text into chunks we want to keep and
        # chunks we want to replace
        # captured text will be replaced. uncaptured text will be kept.
        text = match.group()
        chunks = []
        lastindex = 0
        for i in range(1, pattern.groups+1):
            groupname = groupnames.get(i)
            if groupname not in replacements:
                continue

            # keep the text between this match and the last
            chunks.append(text[lastindex:match.start(i)])
            # then instead of the captured text, insert the replacement text for this group
            chunks.append(replacements[groupname])
            lastindex = match.end(i)
        chunks.append(text[lastindex:])
        # join all the junks to obtain the final string with replacements
        return ''.join(chunks)

    # for each occurence call our custom replacement function
    return re.sub(pattern, repl, string)
>>> replace_groups(pattern, s, {'d': 'aaa', 'm': 'bbb', 'Y': 'ccc'})
'monthday=aaa, month=bbb, year=ccc'
2 of 5
2

You can use string formatting with a regex substitution:

import re
s = 'monthday=1, month=5, year=2018'
s = re.sub('(?<=\=)\d+', '{}', s).format(*['aaa', 'bbb', 'ccc'])

Output:

'monthday=aaa, month=bbb, year=ccc'

Edit: given an arbitrary input string and regex, you can use formatting like so:

input = '2018-12-12'
regex = '((?P<Y>20\d{2})-(?P<m>[0-1]?\d)-(?P<d>\d{2}))'
new_s = re.sub(regex, '{}', input).format(*["aaa", "bbb", "ccc"])
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ regex: can i use numbered capture group references in strings outside of re.sub?
r/learnpython on Reddit: regex: Can I use numbered capture group references in strings outside of re.sub?
January 7, 2022 -

When using re.sub it is possible to use numbered references to refer to each individual match group of the match (as defined by the brackets in the pattern). To showcase:

str1="aaa123-456xxx"
pattern = r"(\d\d\d)-(\d\d\d)"
x=re.sub(pattern, r"\1ABC\2", str1)
print(x)       #output: aaa123ABC456xxx

So, in sub() '\1' refers to my first group content '123' and '\2' to the 2nd '456'.

Is there a way to use this syntax outside of re.sub()? Simply to generate new strings from a regular match object? I know I can access the groups via match.groups(n), but I'd much rather simply use '\n'.

๐ŸŒ
Notepad++ Community
community.notepad-plus-plus.org โ€บ topic โ€บ 20219 โ€บ replace-character-in-capture-group
Replace character in capture group | Notepad++ Community
November 2, 2020 - The Regex Tester that came as a sample script with Python Script looks like I need to study it a bit before I can effectively use it.) A simple solution, to avoid any problem, is to use the Wrap around option and insert an empty line to the very beginning of file ยท Thanks for the warnings. It shouldnโ€™t be a problem with my usage, though. ... Step 1:- Open Notepad++ with the file for replace Step 2:- Replace menu Ctrl+H Step 3:- or Find menu - Ctrl+F Step 4:- Check the Regular expression (at the bottom) Step 5:- Write in Find what Step 6:- \d+ Step 7:- Replace with:X Step 8:- ReplaceAll
๐ŸŒ
YouTube
youtube.com โ€บ watch
Capturing Groups to Search and Replace Text with Regular Expressions - YouTube
Searching and replacing text with regular expressions gives you the ability to sanitize and reformat data with more power and flexibility than you can otherw...
Published ย  May 27, 2020
๐ŸŒ
regex101
regex101.com โ€บ library โ€บ vPdaxv
regex101: use-capture-groups-to-search-and-replace
Discussion of semver and this regex was posted on https://github.com/mojombo/semver.org/issues/59Submitted by @gvlx <Gerardo Lisboa> ... in this exercise we have to use capture groups and then replace the string order to 'three two one'. But first, when you are using the capture group you may have asked yourself why the code below does not work: