Keep case with regex find and replace
Asked Answered
O

3

7

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.

Ob answered 17/3, 2015 at 16:50 Comment(7)
which lang are you running?Kentigera
possible duplicate of How to search replace with regex and keep case as original in javascriptInstall
@AvinashRaj I suppose it is not possible - I was not looking for the answer to be given in a particular language.Ob
it won't be possible through regex alone.Kentigera
@AvinashRaj feel free to answer and say that it is not possible.Ob
This is the proper answer: https://mcmap.net/q/513197/-how-to-search-replace-with-regex-and-keep-case-as-original-in-javascriptWorthington
@Worthington It does preserve the original case if you want to keep the original string, but in this case, dezman is asking for a mapping of case from a distinct but same-length string (Pretty -> Lovely).Grow
K
1

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
Kentigera answered 17/3, 2015 at 17:3 Comment(2)
Note: Built-in functions being callbacks within a regex method. For example: https://mcmap.net/q/513197/-how-to-search-replace-with-regex-and-keep-case-as-original-in-javascriptInstall
@hd this actually need an if else condition in the call-back function.Kentigera
H
0

It is possible with regex alone if using regex version PCRE2.

Pattern : \b(p|(?<upperCase>P))retty\b
Subsititution : ${upperCase:+Lovely:lovely}

In: Pretty pretty is so pretty
Out: Lovely lovely is so lovely

see https://regex101.com/r/1sIqXA/1

Unfortunately, that may not work in your desired programming language.

Hinduism answered 9/8 at 2:25 Comment(1)
this is much closer to a comment than an Answer .. could you add a little more about your solution? meta.stackexchange.com/questions/225370/…Militarize
B
0

Using JS

const str = "Pretty pretty is so pretty";
const result = str.replace(/pretty/gi, (match) => {
return match[0] === 'P' ? 'Lovely' : 'lovely';
});
console.log(result); // "Lovely lovely is so lovely"
Berglund answered 9/8 at 9:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.