2

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 !

JFl
  • 41
  • 5
  • `(\[expr\s+)((?:(\[(?:[^][]++|(?2))*])|[^][{}])*)(])` => `$1{$2}$4`, see https://regex101.com/r/xsKE5u/2. – Wiktor Stribiżew Feb 19 '22 at 14:38
  • @WiktorStribiżew : Thanks ! It works perfectly in regex101 ! However, when I try in Notepad++ to find all expr in a file with this regex, it works fine until the first expr like case c (ending with ]]), any idea why ? But anyway, many thanks, you still save me a lot of time ! – JFl Feb 19 '22 at 15:37
  • Sorry, there is a typo, it must be `(?3)` – Wiktor Stribiżew Feb 19 '22 at 15:41
  • Now it’s also working perfectly in Notepad ! Many Thanks ! I’m curious, can you explain how the middle part of the regex is working ? Thanks ! – JFl Feb 19 '22 at 15:56

1 Answers1

1

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:

enter image description here

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563