Search code examples
regexregex-group

Regular expression for replacing function call with direct access


I'd like to replace a function call in the first format:

get(store, 'data.field1.field2', defaultVal) // there can be more fields on the second part

with this:

data?.field1?.field2 || defaultVal

using regex search replace within the project or possibly using sed or other tools.

I've tried a few expressions but couldn't figure out how to name and split the sections for replace. Any thoughts?


Solution

  • I'd use perl:

    perl -pe 's{get\(.*,\s*'"'"'(.+)'"'"',\s*(.+)\)}{join("?.", split(/\./,$1)) . " || " . $2}ge' file
    

    The get\(.*,\s*'(.+)',\s*(.+)\) regex (see regex demo) matches get(, captures the last two arguments, splits the first one with a dot joining them back with ?. and appends || with the second capture.