Python-Ref > Regular expressions (regexp) > Replacement
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Replacement

Replace pieces of text based on regular expressions.
Regular expressions are often used to replace parts of strings in a specified matter.
Expand/Shrink
Zdroj: (regexp6-1.py)
  1   import re
  2   
  3   text = "I have two dogs. They eat only hotdogs."
  4   
  5   print re.sub( "dog", "cat", text)
  6   
  7   print re.sub( " dog", " cat", text)
  8   
  9   print re.sub( "(?<=\s)dog", "cat", text)
stdout:
I have two cats. They eat only hotcats.
I have two cats. They eat only hotdogs.
I have two cats. They eat only hotdogs.
Doba běhu: 33.2 ms
Usage of groups makes it possible to use parts of the starting text in replacement.
Expand/Shrink
Zdroj: (regexp6-2.py)
  1   import re
  2   
  3   text = "20.12.2006 - Xmass party, 21.12.2006 - hangover to be expected"
  4   
  5   print re.sub( "([0-9]{2})\.([0-9]{2})\.([0-9]{4})", r"\3-\2-\1", text)
stdout:
2006-12-20 - Xmass party, 2006-12-21 - hangover to be expected
Doba běhu: 34.1 ms
Matched groups are available via \1..\99. Because of the usage of the backslash (\) character in python strings literals, it is necessary to either escape the \ character, or use raw-strings, such as r"\9".
Expand/Shrink
Zdroj: (regexp6-3.py)
  1   import re
  2   
  3   text = "20.12.2006 - Xmass party, 21.12.2006 - hangover to be expected"
  4   
  5   print re.sub( "([0-9]{2})\.([0-9]{2})\.([0-9]{4})", r"\3-\2-\1", text)  # ok
  6   print re.sub( "([0-9]{2})\.([0-9]{2})\.([0-9]{4})", "\\3-\\2-\\1", text)  # ok
  7   #print re.sub( "([0-9]{2})\.([0-9]{2})\.([0-9]{4})", "\3-\2-\1", text)  # problem
  8   
stdout:
2006-12-20 - Xmass party, 2006-12-21 - hangover to be expected
2006-12-20 - Xmass party, 2006-12-21 - hangover to be expected
Doba běhu: 29.9 ms