re.sub() - Python RegEx Last Updated : 10 Dec, 2024 Comments Improve Suggest changes Like Article Like Report re.sub() method in Python parts of a string that match a given regular expression pattern with a new substring. This method provides a powerful way to modify strings by replacing specific patterns, which is useful in many real-life tasks like text processing or data cleaning. Python import re a = "apple orange apple banana" pattern = "apple" repl = "grape" # Replace all occurrences of "apple" with "grape" result = re.sub(pattern, repl, a) print(result) Outputgrape orange grape banana Table of ContentSyntax of re.sub()Using Groups in re.sub()Limiting the Number of ReplacementsSyntax of re.sub()re.sub(pattern, repl, string, count=0, flags=0)Parameterspattern: The regular expression pattern we want to match.repl: The string that will replace each match.string: The string where replacements will be made.ReturnThe return type of re.sub() is a string.Using Groups in re.sub()If regular expression has capture groups(defined by parentheses()), we can use the groups in the replacement string using \1,\3,etc., or by using replacement function. Python import re a = "John 25, Jane 30, Jack 22" # Match name and age pattern = r"(\w+) (\d+)" # Use age first, then name repl = r"\2 years old, \1" # Swap names and ages result = re.sub(pattern, repl, a) print(result) Output25 years old, John, 30 years old, Jane, 22 years old, Jack Explanation:This code uses re.sub() to find all matches of a name followed by an age (e.g., "John 25") in the string and swaps the order, placing the age first followed by the name. The replacement string \2 years old, \1 uses the second capture group (age) and the first capture group (name) to format the output.Limiting the Number of ReplacementsTo limit the number of replacements in re.sub(), use the count parameter. By default, count=0, meaning all occurrences are replaced. Specifying a positive integer limits the number of replacements to that value. Python import re a = "apple orange apple banana" pattern = "apple" repl = "grape" # Replace only the first occurrence of "apple" result = re.sub(pattern, repl, a, count=1) print(result) Outputgrape orange apple banana Explanation:This code uses re.sub() to replace only the first occurrence of the word "apple" in the string a with "grape", as specified by the count=1 parameter. Subsequent occurrences of "apple" are left unchanged in the result. Comment More infoAdvertise with us Next Article re.sub() - Python RegEx P pragya22r4 Follow Improve Article Tags : Python python python-regex Practice Tags : pythonpython Similar Reads Python RegEx In this tutorial, you'll learn about RegEx and understand various regular expressions. Regular ExpressionsWhy Regular ExpressionsBasic Regular ExpressionsMore Regular ExpressionsCompiled Regular Expressions A RegEx is a powerful tool for matching text, based on a pre-defined pattern. It can detect t 9 min read Python - Regex split() re.split() method in Python is generally used to split a string by a specified pattern. Its working is similar to the standard split() function but adds more functionality. Letâs start with a simple example of re.split() method:Pythonimport re s = "Geeks,for,Geeks" # Using re.split() to split the st 3 min read re.subn() in Python 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 3 min read Verbose in Python Regex In this article, we will learn about VERBOSE flag of the re package and how to use it. re.VERBOSE : This flag allows you to write regular expressions that look nicer and are more readable by allowing you to visually separate logical sections of the pattern and add comments. Whitespace within the pat 3 min read Regex Cheat Sheet - Python Regex or Regular Expressions are an important part of Python Programming or any other Programming Language. It is used for searching and even replacing the specified text pattern. In the regular expression, a set of characters together form the search pattern. It is also known as the reg-ex pattern. 9 min read Python | re.search() vs re.match() When working with regular expressions (regex) in Python, re.search() and re.match() are two commonly used methods for pattern matching. Both are part of the re module but function differently. The key difference is that re.match() checks for a match only at the beginning of the string, while re.sear 3 min read Python Regex: re.search() VS re.findall() Pythonâs re module provides powerful tools to search, match and manipulate text using regular expressions. Two commonly used functions are re.search(), which finds the first occurrence of a pattern in a string and re.findall(), which retrieves all matches of a pattern throughout the string. Understa 3 min read Python - Regex Lookahead Lookahead is used as an assertion in Python regular expressions to determine success or failure whether the pattern is ahead i.e to the right of the parser's current position. They don't match anything. Hence, they are called as zero-width assertions. Syntax: # Positive lookahead (?=<lookahead_re 2 min read re.search() in Python re.search() method in Python helps to find patterns in strings. It scans through the entire string and returns the first match it finds. This method is part of Python's re-module, which allows us to work with regular expressions (regex) simply. Example:Pythonimport re s = "Hello, welcome to the worl 3 min read replace() in Python to replace a substring replace() method in Python allows us to replace a specific part of a string with a new value. It returns a new string with the change without modifying the original one. We can also specify how many times the replacement should occur.For Example:Pythons = "hlo AB world" # Replace "AB" with "C" in `s 1 min read Like