Python Regex Replace Pattern in a string using re.sub() | python regex replace
Inthisarticle,willlearnhowtouseregularexpressionstoperformsearchandreplaceoperationsonstringsinPython.Pythonregexofferssub()thesubn()methodstosearchandreplacepatternsinastring.Usingthesemethodswecanreplaceoneormoreoccurrencesofaregexpatterninthetargetstringwithasubstitutestring.AfterreadingthisarticleyouwillabletoperformthefollowingregexreplacementoperationsinPython.OperationDescriptionre.sub(pattern,replacement,string)Findandreplacesalloccurrencesofpatternwithreplacementre.sub(pattern,repla...
In this article, will learn how to use regular expressions to perform search and replace operations on strings in Python.
Python regex offers sub() the subn() methods to search and replace patterns in a string. Using these methods we can replace one or more occurrences of a regex pattern in the target string with a substitute string.
After reading this article you will able to perform the following regex replacement operations in Python.
OperationDescriptionre.sub(pattern, replacement, string)Find and replaces all occurrences of pattern with replacementre.sub(pattern, replacement, string, count=1)Find and replaces only the first occurrences of pattern with replacementre.sub(pattern, replacement, string, count=n)Find and replaces first n occurrences of pattern with the replacementPython regex replace operationsBefore moving further, let’s see the syntax of the sub() method.
How to use re.sub() methodTo understand how to use the re.sub() for regex replac...