[Python] Extract a regular expression capture group

Created on November 30, 2026

You can search a string with re and read the text captured by a parenthesized group from the match object. Group numbers start at 1, and group(0) returns the entire match.

import re

pattern = re.compile(r"message_(.+)_world")
match = pattern.search("message_hello_world")
if match:
    print(match.group(1))
hello

search() returns None when there is no match, so check the result before calling group().

Python