1/*
2** Zabbix
3** Copyright (C) 2001-2021 Zabbix SIA
4**
5** This program is free software; you can redistribute it and/or modify
6** it under the terms of the GNU General Public License as published by
7** the Free Software Foundation; either version 2 of the License, or
8** (at your option) any later version.
9**
10** This program is distributed in the hope that it will be useful,
11** but WITHOUT ANY WARRANTY; without even the implied warranty of
12** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13** GNU General Public License for more details.
14**
15** You should have received a copy of the GNU General Public License
16** along with this program; if not, write to the Free Software
17** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18**/
19
20package zbxregexp
21
22import (
23	"bytes"
24	"regexp"
25)
26
27func ExecuteRegex(line []byte, rx *regexp.Regexp, output []byte) (result string, match bool) {
28	matches := rx.FindSubmatchIndex(line)
29	if len(matches) == 0 {
30		return "", false
31	}
32	if len(output) == 0 {
33		return string(line), true
34	}
35
36	buf := &bytes.Buffer{}
37	for len(output) > 0 {
38		pos := bytes.Index(output, []byte{'\\'})
39		if pos == -1 || pos == len(output)-1 {
40			break
41		}
42		_, _ = buf.Write(output[:pos])
43		switch output[pos+1] {
44		case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
45			i := output[pos+1] - '0'
46			if len(matches) >= int(i)*2+2 {
47				if matches[i*2] != -1 {
48					_, _ = buf.Write(line[matches[i*2]:matches[i*2+1]])
49				}
50			}
51			pos++
52		case '@':
53			_, _ = buf.Write(line[matches[0]:matches[1]])
54			pos++
55		case '\\':
56			_ = buf.WriteByte('\\')
57			pos++
58		default:
59			_ = buf.WriteByte('\\')
60		}
61		output = output[pos+1:]
62	}
63	_, _ = buf.Write(output)
64	return buf.String(), true
65}
66