Home > Article > Backend Development > How do you Replace Subgroups in Python Using `re.sub`?
Subgroup Replacement in Python Using re.sub
In Python, the re.sub function allows for performing substitutions based on regular expression patterns. However, when dealing with captured groups within the pattern, it's crucial to understand how to retrieve their values for replacement.
Suppose we want to replace the string "foobar" with "foo123bar" using the re.sub function. Using the pattern "(foo)" to match the "foo" portion, we can encounter issues if we simply replace it with "1123". As demonstrated in the provided example, this will result in an incorrect substitution of "J3bar".
To correctly substitute the group within the pattern, we need to use the "g<1>" syntax. This syntax allows us to refer to the first group captured by the regular expression using its index. Therefore, the correct replacement pattern is "g<1>123":
<code class="python">import re pattern = r'(foo)' result = re.sub(pattern, r'\g<1>123', 'foobar') print(result) # Output: foo123bar</code>
As explained in the documentation, "g<1>" represents the substring matched by the first group. This ensures that the "foo" portion of the original string is replaced with its corresponding value followed by "123".
The above is the detailed content of How do you Replace Subgroups in Python Using `re.sub`?. For more information, please follow other related articles on the PHP Chinese website!