Wednesday, 15 September 2010

regex - How to replace multiple words in a string through Python in a case insensitive way? -



regex - How to replace multiple words in a string through Python in a case insensitive way? -

lets example, have string:

s = 'back in black, nail sack, i've been long i'm glad back.'

in above string, want search & replace words in case insensitive way next words

black : b***

sack : s***

long : l***

glad : g***

i resulting string be

s = 'back in b****, nail s***, i've been l*** i'm glad back.'

basically above string maintains case of first letter of word replacing. letters after word trail '*'

i'm assuming need create list of sort replacements. in django using replace_all() function it's case sensitive. words black , sack, becomes daunting task since there many combinations!

how can go doing this?

use re module, here brief illustration "black":

>>> import re >>> s = "back in black, nail sack, i've been long i'm glad back." >>> regex = re.compile(r'black', flags=re.ignorecase) >>> regex.sub('b***', s) "back in b***, nail sack, i've been long i'm glad back."

to maintain case of first letter, capture , utilize reference in replacement:

>>> regex = re.compile(r'(b)lack', flags=re.ignorecase) >>> regex.sub(r'\1***', s) "back in b***, nail sack, i've been long i'm glad back."

to replacements in 1 pass:

>>> regex = re.compile(r'(?=(.))(?:black|sack|long|glad)', flags=re.ignorecase) >>> regex.sub(r'\1***', s) "back in b***, nail s***, i've been l*** i'm g*** back."

python regex django string replace

No comments:

Post a Comment