Python re (regex) replace examples

Python regular expression module can be used to replace a pattern in a string using re.sub. Basic usage of re.sub is:

re.sub(pattern, repl, string, count=0, flags=0)
## if count > 0: Maximum count occurrences will be replace
## if count=0: All occurrences will be replaces

Here are some examples.

re.sub example using ignore case

Replace foo with bar and use re.I (or re.IGNORECASE) flag for ignoring case.

import re
new = re.sub('foo', 'bar', "foo string1 FOO string2", 0, re.I)
print new
bar string1 bar string2
Env: Python 2.7.6

re.sub – replace whitespaces with dash

Here we’ll replace one or more occurrences of whitespace with dash (-)

import re
new = re.sub('[\s]+', '-', "hello    world\n\nhello2")
print new
hello-world-hello2
Env: Python 2.7.6

re.sub remove c like comments using dot matches all

Replace c like comments from a multiline string

import re
str = "/*line1\nline2*/\ni=0\n/*comment2*/\nj=1\n"
new = re.sub('/\*.*?\*/', '', str, 0, re.S)
print "===before sub ==="
print str
print "===after sub ==="
print new
===before sub ===
/*line1
line2*/
i=0
/*comment2*/
j=1

===after sub ===

i=0

j=1

Env: Python 2.7.6
Note that we are using greedy regex here (.*?) to avoid matching with end of second comment section.

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments