Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #369 Parse matching brackets

Generate a collection, a, of index-values, given the text, s, containing paired bracket values.

For example, "{ { } } { }" is `(0, 6) (2, 4) (8, 10)`.

https://en.wikipedia.org/wiki/Bracket_(mathematics)
https://en.wikipedia.org/wiki/Scope_(computer_science)

#include <vector>
using namespace std;
struct xy { int x, y; };
vector<xy> a;
int x, y, m (s.size()), n, c;
for (x = 0; x not_eq m; ++x)
    if (s[x] == '{')
        for (y = x + (n = 1); y not_eq m; ++y)
            if ((c = s[y]) == '{') ++n;
            else if (c == '}' and not --n) {
                a.push_back({x, y});
                break;
            }
import java.util.ArrayList;
import java.util.List;
record XY(int x, int y) {}
List<XY> a = new ArrayList<>();
int x, y, m = s.length(), n, c;
for (x = 0; x != m; ++x)
    if (s.charAt(x) == '{')
        for (y = x + (n = 1); y != m; ++y)
            if ((c = s.charAt(y)) == '{') ++n;
            else if (c == '}' && --n == 0) {
                a.add(new XY(x, y));
                break;
            }
var
  i, k,B,Len: Integer;
  List: array of integer;
  c: Char;
const
  S = '{.{.}.}.{.}';
begin
  SetLength(List,Length(S));
  Len:=Length(S);
  for i:=1 to Len do begin
    if S[i]='{' then begin
      B:=0;
      for k:=i+1 to Len do begin
        c:=S[k];
        if c='{' then
          Inc(B)
        else
          if c = '}' then begin
            if (B<=0) then Break;
            Dec(B);
          end;
      end;
      List[i-1]:=k-1;
    end
    else
      List[i-1]:=-1;
  end;
end.
a = []
x, m = 0, len(s)
while x != m:
    if s[x] == '{':
        y = x + (n := 1)
        while y != m:
            match s[y]:
                case '{': n += 1
                case '}':
                    if not (n := n - 1):
                        a.append((x, y))
                        break
            y += 1
    x += 1

New implementation...
< >
reilas