File: match_br.awk

package info (click to toggle)
runawk 1.6.1-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 712 kB
  • sloc: awk: 1,127; ansic: 736; sh: 420; makefile: 103
file content (52 lines) | stat: -rw-r--r-- 1,004 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# Written by Aleksey Cheusov <vle@gmx.net>, public domain
#
# This awk module is a part of RunAWK distribution,
#        http://sourceforge.net/projects/runawk
#    
############################################################

# =head2 match_br.awk
#
# =over 2
#
# =item I<match_br(STRING, BR_OPEN, BR_CLOSE)>
#
# return start position (or zero if failure) of the substring
# surrounded by balanced (), [], {} or similar characters
# Also sets RSTART and RLENGTH variables just like
# the standard 'match' function does
#  
# For example:
#   print match_br("A (B (), C(D,C,F (), 123))", "(", ")")
#   print RSTART, RLENGTH
#   -| 3
#   -| 3
#   -| 24
#
# =back
#

function match_br (s, br_open, br_close,                len,i,cnt){
	len = length(s)
	cnt = 0
	for (i=1; i <= len; ++i){
		ch = substr(s, i, 1)

		if (ch == br_open){
			if (cnt == 0){
				RSTART = i
			}

			++cnt
		}else if (ch == br_close){
			--cnt

			if (cnt == 0){
				RLENGTH=i-RSTART+1
				return RSTART
			}
		}
	}

	return 0
}