Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't ignorecase flag (re.I) work in re.sub() [duplicate]

Tags:

python

regex

From pydoc:

re.sub = sub(pattern, repl, string, count=0, flags=0)
Return the string obtained by replacing the leftmost non-overlapping occurrences of the pattern in string by the replacement repl. repl can be either a string or a callable; if a string, backslash escapes in it are processed. If it is a callable, it's passed the match object and must return a replacement string to be used.

example code:

import re print re.sub('class', 'function', 'Class object', re.I) 

No replacement is made unless I change pattern to 'Class'.

Documentation doesn't mention anything about this limitation, so I assume I may be doing something wrong.

What's the case here?

like image 623
theta Avatar asked Jan 11 '12 02:01

theta


People also ask

Does re sub replace all occurrences?

By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.

What is Flags in re sub?

The full definition of re.sub is: re.sub(pattern, repl, string[, count, flags]) Which means that if you tell Python what the parameters are, then you can pass flags without passing count : re.sub('^//', '', s, flags=re.MULTILINE) or, more concisely: re.sub('^//', '', s, flags=re.M)

What does re sub () do?

sub() function belongs to the Regular Expressions ( re ) module in Python. It returns a string where all matching occurrences of the specified pattern are replaced by the replace string.


2 Answers

Seems to me that you should be doing:

import re print(re.sub('class', 'function', 'Class object', flags=re.I)) 

Without this, the re.I argument is passed to the count argument.

like image 199
André Caron Avatar answered Sep 23 '22 17:09

André Caron


The flags argument is the fifth one - you're passing the value of re.I as the count argument (an easy mistake to make).

like image 25
ekhumoro Avatar answered Sep 22 '22 17:09

ekhumoro