Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace all occurrences that match regular expression

Tags:

python

regex

I have a regular expression that searches for a string that contains '.00.' or '.11.' as follows:

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

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

I was looking into the Python re.sub method and am unsure of how to do this effectively. The returned match object only matches on the first occurrence and therefore doesn't work well. Any advice? Should I just be using a string replace for this task? Thanks.

like image 383
tots_o_tater Avatar asked Jul 02 '16 05:07

tots_o_tater


People also ask

How do you replace all occurrences of a regex pattern in a string?

count : Maximum number of pattern occurrences to be replaced. The count must always be a positive integer if specified. . By default, the count is set to zero, which means the re. sub() method will replace all pattern occurrences in the target string.

How do you replace all occurrences in a string?

To replace all occurrences of a substring in a string by a new one, you can use the replace() or replaceAll() method: replace() : turn the substring into a regular expression and use the g flag.

Can you use regex to replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.


1 Answers

re.sub() (docs for Python 2 and Python 3) does replace all matches it finds, but your use of .* may have caused the regex to match too much (even other occurences of .00. etc.). Simply do:

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

Note that patterns cannot overlap:

In [3]: re.sub(r"\.(00|11)\.", r"X\1X", ".00.11.") Out[3]: 'X00X11.' 
like image 191
Tim Pietzcker Avatar answered Sep 19 '22 17:09

Tim Pietzcker