+44

Support Python functions within regex replace strings

Joel Thornton 6 years ago • updated by Jonathan Cross 5 years ago 2
Let us embed simple Python expressions in the ST2 search-and-replace "replace with" box that would let us perform transformations on captured text groups when using regular expression matching. 

A syntax looking something like this might work well:

Search regex: (\w+)
Replace with: ${$1.upper()}

In this example ST2 would recognize a special pattern of 
${PYTHON_FUNCTION}
and implicitly give $n the string value of the corresponding capture group within the function.

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

${ int($1) + 1 }
${ max($1, $2) }
${ import re; re.sub('foo', 'bar', $1) if 'foo' in $1 else 'cheezburger' }
... ad inf.

Nice to know that the idea is being picked up by others...

If the feature would be as advanced as suggested here it would be nice to see some examples or a link to a simple Python reference. While I and probably many other non-Python users would be able to figure out the allowed syntax somehow it can get annoying if you need to do so every time because you forgot some things about it.

For simple upper / lower casing, other editors like TextPad support a much more simple syntax in "replacement expressions":
  • \u  Force the next substituted character to be in upper case.
  • \l  Force the next substituted character to be in lower case.
  • \U  Force all subsequent substituted characters to be in upper case.
  • \L  Force all subsequent substituted characters to be in lower case.
  • \E or \e  Turns off previous \U or \L.