diff --git a/model/relabel/relabel.go b/model/relabel/relabel.go index 98a245bba..687ac03d0 100644 --- a/model/relabel/relabel.go +++ b/model/relabel/relabel.go @@ -142,17 +142,13 @@ func (c *Config) UnmarshalYAML(unmarshal func(interface{}) error) error { // Regexp encapsulates a regexp.Regexp and makes it YAML marshalable. type Regexp struct { *regexp.Regexp - original string } // NewRegexp creates a new anchored Regexp and returns an error if the // passed-in regular expression does not compile. func NewRegexp(s string) (Regexp, error) { regex, err := regexp.Compile("^(?:" + s + ")$") - return Regexp{ - Regexp: regex, - original: s, - }, err + return Regexp{Regexp: regex}, err } // MustNewRegexp works like NewRegexp, but panics if the regular expression does not compile. @@ -180,12 +176,19 @@ func (re *Regexp) UnmarshalYAML(unmarshal func(interface{}) error) error { // MarshalYAML implements the yaml.Marshaler interface. func (re Regexp) MarshalYAML() (interface{}, error) { - if re.original != "" { - return re.original, nil + if re.String() != "" { + return re.String(), nil } return nil, nil } +// String returns the original string used to compile the regular expression. +func (re Regexp) String() string { + str := re.Regexp.String() + // Trim the anchor `^(?:` prefix and `)$` suffix. + return str[4 : len(str)-2] +} + // Process returns a relabeled copy of the given label set. The relabel configurations // are applied in order of input. // If a label set is dropped, nil is returned. diff --git a/model/relabel/relabel_test.go b/model/relabel/relabel_test.go index 4ae1f5344..5e9bd1438 100644 --- a/model/relabel/relabel_test.go +++ b/model/relabel/relabel_test.go @@ -461,7 +461,7 @@ func TestRelabel(t *testing.T) { if cfg.Separator == "" { cfg.Separator = DefaultRelabelConfig.Separator } - if cfg.Regex.original == "" { + if cfg.Regex.Regexp == nil || cfg.Regex.String() == "" { cfg.Regex = DefaultRelabelConfig.Regex } if cfg.Replacement == "" {