Python regexp replace group

How to Replace Group using Regex Replace in Python

To replace a group using a regex in Python, use the “re.sub()” method and include the group you want to replace in the regular expression.

Syntax

The syntax of the sub() method is re.sub(pattern, repl, string, count=0, flags=0).

  1. pattern: It is the regex pattern for the group to be replaced.
  2. replay: It is the replacement string.
  3. string: It is the string in which the replacement will be performed.
  4. count: It is the maximum number of replacements to make.
  5. flags: They are the regex flags to use.

The syntax consists of various metacharacters to indicate the pattern you are looking for.

Python regex replace approach replaces a group of characters with a new string in the text. It can find a specific word or phrase and replace it with a different one.

For example, the metacharacter ‘\d’ indicates that you want to find digits, or ‘\s’ suggests that you want to find whitespace.

Example 1

To use the re.sub() method in Python, import the built-in re module.

import re str = "you are the world, you are the children!" result = re.sub(r"you", "we", str) print(result)
we are the world, we are the children!

In this example, we replaced a group of strings “you” with “we” using the re.sub() method.

Example 2

Replace each substring of the string with a provided string using the re.sub() method.

import re str = "you are the world, you are the children!" output_value = re.sub(r"(\w+)", r"kb", str) print(output_value)

We replaced each substring of a string with a provided string using the re.sub() method in one go.

Leave a Comment Cancel reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Источник

Читайте также:  Операторы присваивания в языке программирования python
Оцените статью