![]() |
VOOZH | about |
re.subn() method in Python is used to search for a pattern in a string and replace it with a new substring. It not only performs the replacement but also tells us how many times the replacement was made. We can use this method when we need to replace patterns or regular expressions in text and get a count of how many changes were made. We can do this using the re.subn() method in the re module.
Let's understand this with the help of example:
Geeks for Geeks Replacements made: 0
The syntax for the re.subn() method is as follows:
re.subn(pattern, repl, string, count=0, flags=0)
We can also use regular expressions to replace patterns that match more complex rules, not just fixed strings. This code uses a regular expression to find phone numbers in a specific format (xxx-xxx-xxxx) and replaces them with a placeholder XXX-XXX-XXXX. The code also prints how many replacements were made.
My phone number is XXX-XXX-XXXX and my friend's is XXX-XXX-XXXX 2
If we want to replace words regardless of their case, we can use the re.IGNORECASE flag. This code uses a regular expression to find occurrences of the word "test", regardless of case.
This is a exam. This is another exam. Replacements made: 2
This example replaces all HTML tags with the placeholder [TAG] and counts how many tags were replaced. This code is useful for sanitizing or cleaning HTML tags.
[TAG]Hello[TAG] [TAG]World[TAG] 4