How to match range of numbers if text includes above 255?

Solution 1:

First of all, those (?<= ) and (?= ) lookaheads should be outside the (numbers) group, not inside. For example, right now, the initial "space before" (?<= ) operator only applies to 1[0-1][6-9] – it doesn't apply to all other |-separated alternatives! Your regex actually matches "abcdef200" even though there is no space separation.

(And it also matches values from 100, not from 106, because of the "1[0-9][0-9]" part.)

So you should have used:

editor.rereplace('(?<= )(1[0-1][6-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(?= )',
                 calculate)

The main regex in the middle is just long, but not actually complex – it's just a |-separated list of options that enumerate all possible ways the number can look.

For example, if you want to match numbers 106 to 637, they can be grouped like this (last digit, last 2 digits, all 3 digits, and back the same way):

  • 106 to 109: 10[6-9]
  • 110 to 199 (really 11_ to 19_): 1[1-9][0-9]
  • 200 to 599 (really 2__ to 5__): [2-5][0-9][0-9]
  • 600 to 629 (really 60_ to 62_): 6[0-2][0-9]
  • 630 to 637: 63[0-7]

So the final regex would look like:

(?<= )(10[6-9]|1[1-9][0-9]|[2-5][0-9][0-9]|6[0-2][0-9]|63[0-7])(?= )

However, you have Python. You don't need to cram literally all of your logic into the regex – you can match all numbers first, and let the Python callback decide on replacement for each result:

def calculate(match):
    number = int(match.group(1))
    if 106 <= number <= 637:
        return str(number + 4)
    else:
        return str(number)

editor.rereplace('(?<= )([0-9]{3})(?= )', calculate)

The [0-9]{3} matches all 3-digit numbers (as a slight precaution), and replaces them either with themselves or with the incremented value.