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 !
You can use
Find What: (\[expr\s+)((?:(\[(?:[^][]++|(?3))*])|[^][{}])*)(])
Replace With: $1{$2}$4
See the regex demo. Details:
(\[expr\s+)
- Group 1:((?:(\[(?:[^][]++|(?3))*])|[^][{}])*)
- Group 2: zero or more occurrences of
(\[(?:[^][]++|(?3))*])
- Group 3: [
, then zero or more sequences of any one or more chars other than [
and ]
or Group 3 pattern recursed, and then a ]
char|
- or[^][{}]
- a char other than [
, ]
, {
and }
(])
- Group 4: a ]
char.Demo screenshot: