Problem: Finding and replacing text in a string
Solution:
1. For simple mode: str.replace (old, new[, Max])
2. Complex mode: Use the re.sub ( matching mode , newstring, oldstring[, replace number]) function in the RE module
3, RE.SUBN () can get the total number of replacements
#example.py##Examples of simple regular expression substitutionImportRe#Simple Sampletext1='yeah,but no,but yeah,but no,but yeah,but no,but Yeah'Print(Text1.replace ('Yeah','Yeh'))Print(Text1.replace ('No','Yes', 2))Print('---------------------------')
#Some Sample TextText ='Today is 11/27/2012. Pycon starts 3/13/2013.'Datepat= Re.compile (r'(\d+)/(\d+)/(\d+)')#(a) simple substitution \3-represents the 3rd pattern group in a matching patternPrint(Datepat.sub (R'\3-\1-\2', text)) #equivalent to print (Re.sub (R ' (\d+)/(\d+)/(\d+) ', R ' \3-\1-\2 ', text))Print('*****************************')
#(b) Replacement function substitution callback functions fromCalendarImportMonth_abbrdefchange_date (m): Mon_name= Month_abbr[int (M.group (1))] return '{} {} {}'. Format (M.group (2), Mon_name, M.group (3))Print(Datepat.sub (change_date, text))Print(Re.sub (R'(\d+)/(\d+)/(\d+)', Change_date, text))Print('++++++++++++++++++++++++++++++++')
# Total number of replacements obtained by RE.SUBN ()
newtext,n =datepat.subn (r " \3-\1-\2 " , text)
print (NewText)
print (N)
>>> ================================ RESTART ================================>>> yeh,but No, But yeh,but no,but yeh,but no,but yehyeah,but yes,but yeah,but yes,but yeah,but no,but yeah------------------------- - -is 2012-11-27. Pycon starts 2013-3-13. is 2012. Pycon starts is 2012. Pycon starts. ++++++++++++++++++++++++++++++++ is 2012-11-27. Pycon starts 2013-3-13.
Python Cookbook "String and Text" 5. Find and replace text