I’m looking for applications and programming language constructs to search for a regular expression pattern, transform the match in some way and then replace it. A very simple example: Transforming “myCamelCasedString” to “my_camel_cased_string”.
In Ruby it’s easy and concise:
s = "myCamelCasedString".gsub(/[A-Z]/) { |m| "_" + m.downcase }
In PHP it’s longer, but also possible
preg_replace_callback('/[A-Z]/',
// Using PHP 5.3 anonymous function as callback
function($m) { return "_" . strtolower($m[0]); },
"myCamelCasedString");
The text editor jEdit also supports this through a “Beanshell snippet” but I always have to look up how to do it. So – how would I do this in other languages and is there a dedicated application/editor that lets me do this (together with a handy reference of possible transformations)?
I think Ruby is the dedicated application you’re looking for:
The data:
The scriptlet:
The magic sauce is the “-p” switch. It wraps the code provided with the “-e” switch in “while gets (); … ; print $_ end”. ‘$_’ is a Perlish variable which holds the most recently read line.