diff --git a/retrieval/relabel.go b/retrieval/relabel.go index ec6af2eee..f63486889 100644 --- a/retrieval/relabel.go +++ b/retrieval/relabel.go @@ -47,12 +47,13 @@ func relabel(labels clientmodel.LabelSet, cfg *config.RelabelConfig) (clientmode return nil, nil } case config.RelabelReplace: + indexes := cfg.Regex.FindStringSubmatchIndex(val) // If there is no match no replacement must take place. - if !cfg.Regex.MatchString(val) { + if indexes == nil { break } - res := cfg.Regex.ReplaceAllString(val, cfg.Replacement) - if res == "" { + res := cfg.Regex.ExpandString([]byte{}, cfg.Replacement, val, indexes) + if len(res) == 0 { delete(labels, cfg.TargetLabel) } else { labels[cfg.TargetLabel] = clientmodel.LabelValue(res) diff --git a/retrieval/relabel_test.go b/retrieval/relabel_test.go index 984fbc187..42a6509b2 100644 --- a/retrieval/relabel_test.go +++ b/retrieval/relabel_test.go @@ -90,6 +90,25 @@ func TestRelabel(t *testing.T) { }, output: nil, }, + { + input: clientmodel.LabelSet{ + "a": "abc", + }, + relabel: []*config.RelabelConfig{ + { + SourceLabels: clientmodel.LabelNames{"a"}, + Regex: &config.Regexp{*regexp.MustCompile("(b)")}, + TargetLabel: clientmodel.LabelName("d"), + Separator: ";", + Replacement: "$1", + Action: config.RelabelReplace, + }, + }, + output: clientmodel.LabelSet{ + "a": "abc", + "d": "b", + }, + }, { input: clientmodel.LabelSet{ "a": "foo",