regexfind-replacerecursive-regex

Regex to find a specific pattern in code and replace it with a new pattern


I’m new to regex and I can’t find a way to do what I want. Let me explain. I have some piece of code that looks like this in Notepad++:

set a [expr $sumy+1]
set b [[expr $sumy+1] [expr $sumy+2] [expr $sumy+3]]
set c [expr $sumy+[lindex $coords 1]]
set d [expr [lindex [$ret] 2] + $Alpha]
set e [string range $SECNAME 0 [expr [string first - $SECNAME] -1] ]

And I have to remplace each [expr … ] pattern by [expr {…}] (and if brackets are already there, it must not be replaced) :

set a [expr {$sumy+1}]
set b [[expr {$sumy+1}] [expr {$sumy+2}] [expr {$sumy+3}]]
set c [expr {$sumy+[lindex $coords 1]}]
set d [expr {[lindex [$ret] 2] + $Alpha}]
set e [string range $SECNAME 0 [expr {[string first - $SECNAME] -1}] ]

To do the job, I’m using regex to find each expr pattern and replace it with the new one. For cases a and b, this regex works fine :

Find : (\[expr\s+)([^{][^\]]*)(\]) Replace : \1{\2}\3

For cases c and d, I’m using this one :

Find : ((\[expr\s+)([^{][^\].*\]]*)(\].*)(\])) Replace : \1{\2\3}\4 (https://regex101.com/r/ZU6mNd/1)

But I don’t find a way to match properly the expr pattern for case e. Can anyone help me with that ? I was also wondering if there is a way to match all the cases with a single regex ? Maybe with recursion ?

Thanks !


Solution

  • You can use

    Find What:      (\[expr\s+)((?:(\[(?:[^][]++|(?3))*])|[^][{}])*)(])
    Replace With: $1{$2}$4

    See the regex demo. Details:

    Demo screenshot:

    enter image description here