Padarom Padarom - 4 months ago 36
Brainfuck Question

Regex for brainfuck loops

I'd like to create a regular expression that is able to fetch every loop inside a brainfuck code.

Let's say this code is given:

++++[>+[>,++.]<<-]++[>,.<-]


I want to fetch these three loops (actually it would be sufficient just to fetch the first one):

[>+[>,++.]<<-]
[>,++.]
[,.<-]


My knowledge of regular expressions is pretty weak, so I can't do much more than basics. What I have thought of is this expression:

\[[-+><.,\[\]]*]

\[ - Match the first (opening) bracket
[-+><.,\[\]]* - followed by a number of brainfuck operators
] - followed by a closing bracket


This however matches (obviously) everything between the first opening, and the last closing bracket:

[>+[>,++.]<<-]++[>,.<-]


It might need something to test for the same number of opening and closing brackets inside the loop, before matching the last closing bracket - If that makes any sense.

Maybe a lookaround (I need to use this in javascript, so I can only use lookaheads) is the right way to do this, but I can't figure out how it's supposed to be done.

Answer

I had written this one once when I needed to match a pair of square brackets (while handling nesting correctly)

It is a .NET regex that uses some features that aren't available in all regex engines. Here goes:

\[(?>\[(?<d>)|\](?<-d>)|.?)*(?(d)(?!))\]