Martin Schmelzer
Martin Schmelzer

Reputation: 23919

Conditional replacement of numbers with regex

Input:

foobar10000foobar
foobar1000foobar
foobar100foobar
foobar10foobar
foobarfoobar

Desired Output:

foobar4foobar
foobar3foobar
foobar2foobar
foobar1foobar
foobar0foobar

In other words, the replacements should be the number of zeros contained in the matched numbers. The examples already contain all possible numbers: {none, 10, 100, 1000, 10000} .

Is there a way to do it with one regex statement?

(Side info: I want to implement a rule for the RegReplace package for Sublime Text 3)

Upvotes: 2

Views: 290

Answers (1)

Thierry Lathuille
Thierry Lathuille

Reputation: 24290

You can, as re.sub accepts a function as replacement. See re.sub

The replacement function takes a match object as parameter, and must return a string.

import re
texts = ['foobar10000foobar', 'foobar100foobar',
         'foobar1foobar', 'foobarfoobar']

def zeros_count(matchobj):
     return str(matchobj.group(0).count('0'))

def replace_zeros(text):
    return re.sub(r'\d+', zeros_count, text)

for text in texts:
    print(text, '-->', replace_zeros(text))

# foobar10000foobar --> foobar4foobar
# foobar100foobar --> foobar2foobar
# foobar1foobar --> foobar0foobar
# foobarfoobar --> foobarfoobar

Note that in the last case, there's no number to replace, so there is no logical place to insert a 0, as in your last desired output.

Upvotes: 3

Related Questions