Home > Back-end >  Regex to find a specific pattern in code and replace it with a new pattern
Regex to find a specific pattern in code and replace it with a new pattern

Time:02-20

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 (enter image description here

  • Related