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.18
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.18
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.18
.*?
) to avoid matching with end of second comment section.