简体   繁体   中英

Replace the wrapper (parent) string by regular expression and preserve the inner child content

I have multiple files which have obsolete format and I would like to replace them with the latest format. One of my trouble is finding all the wrapper string and replace them all while I have to preserve their inner content.

Example

I want to convert an expression ABC($IGNORE$) to XBD([$IGNORE$])->T . Here is the string the format of which needs updating.

Input :

... ABC( ......
..... (inner content should not be changed) .....
......) ....

Output :

... XBD([ ......
..... (inner content should not be changed) .....
......])->T ....

How do I achieve it?

You can use the following regex that is able to match nested round brackets:

\bABC(\(((?>[^()]+)|(?-2))*\))

Replace with XBD$1->T .

See demo

Sample PHP code :

<?php
    $re = "#\bABC(\(((?>[^()]+)|(?-2))*\))#"; 
    $str = "ABC( ......\n..... (inner content should not be changed) .....\n......) "; 
    $subst = "XBD$1->T"; 
    echo $result = preg_replace($re, $subst, $str);
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM