Replace all occurrences matching the regular expression

I have a regex that searches for a string containing '.00.' or '.11.' in the following way:

 .*\.(00|11)\..* 

What I would like to do is replace all occurrences matching the pattern with 'X00X' or 'X11X' . For example, the string '.00..0..11.' will result in 'X00X.0.X11X' .

I studied the re.sub method of Python and don't know how to do this efficiently. The returned matching object matches only the first occurrence and therefore does not work. Any advice? Should I use string replacement for this task? Thanks.

+7
python regex
source share
1 answer

re.sub() replaces all matches found, but using .* can cause the regex to match too much (even other occurrences of .00. , etc.). Just do:

 In [2]: re.sub(r"\.(00|11)\.", r"X\1X", ".00..0..11.") Out[2]: 'X00X.0.X11X' 

Please note that patterns cannot overlap:

 In [3]: re.sub(r"\.(00|11)\.", r"X\1X", ".00.11.") Out[3]: 'X00X11.' 
+9
source share

All Articles