regex implementation to replace group with its lowercase version

Viewed 47478

Is there any implementation of regex that allow to replace group in regex with lowercase version of it?

6 Answers

If your regex version supports it, you can use \L, like so in a POSIX shell:

sed -r 's/(^.*)/\L\1/'

In Perl, you can do:

$string =~ s/(some_regex)/lc($1)/ge;

The /e option causes the replacement expression to be interpreted as Perl code to be evaluated, whose return value is used as the final replacement value. lc($x) returns the lowercased version of $x. (Not sure but I assume lc() will handle international characters correctly in recent Perl versions.)

/g means match globally. Omit the g if you only want a single replacement.

In Perl, there's

$string =~ tr/[A-Z]/[a-z]/;

Most Regex implementations allow you to pass a callback function when doing a replace, hence you can simply return a lowercase version of the match from the callback.

Related