+5

RegEx replace with math on captured numbers

Chris S. 6 years ago • updated by Joel Thornton 6 years ago 2

It would be very cool if we could do enhanced replacing with regular expressions that capture numbers.


I would like to write a regular expression that captures a number and then make use of the captured number in the replace field and add an offset to it for example.


This would be very useful for files that contain positions or coordinates which need an offset.

+4
I agree this would be useful to have. 


This is actually a typical limitation of most regex implementations, because basic regex substitution really only works with the text chunks and has no built-in facility for doing computations against the text chunks. Arguably this is the right behavior for the regex standard, as it would otherwise have to embed a full-fledged programming language in the replacement syntax to account for any desired transforms.


Most modern programming languages -- like Python, which ST2 is written in -- will indeed allow you to apply custom functions to captured match-groups.


So, a more comprehensive solution might be to let us embed simple Python expressions in the ST2 "replace with" box that would let us perform computations as desired. For example, a syntax looking something like this might do the trick:


Search regex: (\d+)

Replace with: ${int($1) + 1}


In this example ST2 would recognize a special pattern of
${PYTHON_FUNCTION}

and implicitly give $n the value of the corresponding capture group within the function.


This approach could open up some very interesting possibilities for doing regex replacement...


${$1.upper()}

${max($1, $2)}

etc.

I really like this idea so I created a separate UserEcho entry for it.