1# Written by Aleksey Cheusov <vle@gmx.net>, public domain
2#
3# This awk module is a part of RunAWK distribution,
4#        http://sourceforge.net/projects/runawk
5#
6############################################################
7
8# =head2 match_br.awk
9#
10# =over 2
11#
12# =item I<match_br(STRING, BR_OPEN, BR_CLOSE)>
13#
14# return start position (or zero if failure) of the substring
15# surrounded by balanced (), [], {} or similar characters
16# Also sets RSTART and RLENGTH variables just like
17# the standard 'match' function does
18#
19# For example:
20#   print match_br("A (B (), C(D,C,F (), 123))", "(", ")")
21#   print RSTART, RLENGTH
22#   -| 3
23#   -| 3
24#   -| 24
25#
26# =back
27#
28
29function match_br (s, br_open, br_close,                len,i,cnt){
30	len = length(s)
31	cnt = 0
32	for (i=1; i <= len; ++i){
33		ch = substr(s, i, 1)
34
35		if (ch == br_open){
36			if (cnt == 0){
37				RSTART = i
38			}
39
40			++cnt
41		}else if (ch == br_close){
42			--cnt
43
44			if (cnt == 0){
45				RLENGTH=i-RSTART+1
46				return RSTART
47			}
48		}
49	}
50
51	return 0
52}
53