Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep case with regex find and replace

Tags:

regex

My question is pretty straightforward, using only a regular expression find and replace, is it possible to keep the case of the original words.

So if I have the string: "Pretty pretty is so pretty" How can I turn it into: "Lovely lovely is so lovely"

All I have so far is find /(P|p)retty/g and replace with $1ovely but I dont know how to replace caplital P with L and lowercase p with l.

I am not interested in accomplishing this in any particular language, I want to know if it is possible to do with pure regex.

like image 615
dezman Avatar asked Mar 17 '15 16:03

dezman


1 Answers

It can't be possible to replace captured uppercase or lowercase letter with the letter according to the type of letter captured through regex alone. But it can be possible through language built-in functions + regex.

In php, i would do like.

$str = "Pretty pretty is so pretty";
echo preg_replace_callback('~([pP])retty~', function ($m)
        { 
            if($m[1] == "P") {
            return "Lovely"; }
            else { return "lovely"; }
        }, $str);

Output:

Lovely lovely is so lovely
like image 96
Avinash Raj Avatar answered Sep 30 '22 19:09

Avinash Raj