Home >Backend Development >Python Tutorial >How to Use Group Numbers in Regular Expression Substitution in Python?

How to Use Group Numbers in Regular Expression Substitution in Python?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 13:23:30903browse

How to Use Group Numbers in Regular Expression Substitution in Python?

Replacement with Group Number in Regular Expression Substitution

When attempting to replace a placeholder with a group number followed by a specified string, the statement re.sub(r'(foo)', r'1123', 'foobar') fails, resulting in 'J3bar'. This is because the numeric portion is interpreted literally and not as a backreference to the group.

To resolve this, one can utilize the g syntax, where group_number denotes the group to be referenced. For example, re.sub(r'(foo)', r'g<1>123', 'foobar') effectively replaces 'foobar' with 'foo123bar'.

The Python documentation explains this functionality as follows:

  • g references the substring matched by a group named 'name'.
  • g references the corresponding group number.
  • g<0> references the entire substring matched by the regular expression.

The above is the detailed content of How to Use Group Numbers in Regular Expression Substitution in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn