{"record":{"id":"bd7aa7b37b7bf29f","repo":"prometheus/prometheus","slug":"invalid-regular-expression-in-label-replace-s","errorCode":null,"errorMessage":"invalid regular expression in label_replace(): %s","messagePattern":"invalid regular expression in label_replace\\(\\): (.+?)","errorType":"panic","errorClass":null,"httpStatus":null,"severity":"error","filePath":"promql/functions.go","lineNumber":2493,"sourceCode":"\t\t}\n\t\tprevSample = curSample\n\t}\n\n\treturn append(enh.Out, Sample{F: float64(changes)}), nil\n}\n\n// label_replace function operates only on series; does not look at timestamps or values.\nfunc (ev *evaluator) evalLabelReplace(ctx context.Context, args parser.Expressions) (parser.Value, annotations.Annotations) {\n\tvar (\n\t\tdst      = stringFromArg(args[1])\n\t\trepl     = stringFromArg(args[2])\n\t\tsrc      = stringFromArg(args[3])\n\t\tregexStr = stringFromArg(args[4])\n\t)\n\n\tregex, err := regexp.Compile(\"^(?s:\" + regexStr + \")$\")\n\tif err != nil {\n\t\tpanic(fmt.Errorf(\"invalid regular expression in label_replace(): %s\", regexStr))\n\t}\n\tif !model.UTF8Validation.IsValidLabelName(dst) {\n\t\tpanic(fmt.Errorf(\"invalid destination label name in label_replace(): %s\", dst))\n\t}\n\n\tval, ws := ev.eval(ctx, args[0])\n\tmatrix := val.(Matrix)\n\tlb := labels.NewBuilder(labels.EmptyLabels())\n\n\tfor i, el := range matrix {\n\t\tsrcVal := el.Metric.Get(src)\n\t\tindexes := regex.FindStringSubmatchIndex(srcVal)\n\t\tif indexes != nil { // Only replace when regexp matches.\n\t\t\tres := regex.ExpandString([]byte{}, repl, srcVal, indexes)\n\t\t\tlb.Reset(el.Metric)\n\t\t\tlb.Set(dst, string(res))\n\t\t\tmatrix[i].Metric = lb.Labels()\n\t\t\tif dst == model.MetricNameLabel {","sourceCodeStart":2475,"sourceCodeEnd":2511,"githubUrl":"https://github.com/prometheus/prometheus/blob/44d6a0e0b1dbdcba4e68853d50e0bafc87d90507/promql/functions.go#L2475-L2511","documentation":"evalLabelReplace compiles the regular expression wrapped as ^(?s:<regex>)$ before evaluating the inner vector. If the user-supplied regex in label_replace(v, dst, repl, src, regex) does not compile, the evaluator panics with 'invalid regular expression in label_replace(): <regex>'; the query engine recovers the panic and returns it as a query error at the offending position.","triggerScenarios":"Calling label_replace with a syntactically invalid Go regexp: unbalanced parentheses, invalid escapes like '\\d' (Go uses \\d but not \\z style PCRE syntax such as lookaheads (?=...)), or stray repetition like '*', e.g. label_replace(up, \"a\", \"$1\", \"job\", \"(.*)extra)\").","commonSituations":"Porting regexes from PCRE/Python/JS (lookaheads, backreferences not supported by RE2); dynamic regex built from label values containing metacharacters; escaping mistakes when embedding regex in YAML rules (double-escaping issues).","solutions":["Fix the regex to valid RE2/Go syntax (test with Go's regexp or an RE2 tester; remove lookaheads/backreferences)","Mind YAML escaping in rules files: use single quotes or double the backslashes appropriately","If the regex is dynamic, sanitize/validate it before injecting into the query","Test with a minimal query in the UI expression browser first"],"exampleFix":"# before (PCRE lookahead, invalid in RE2)\nlabel_replace(up, \"d\", \"$1\", \"instance\", \"([^:]+)(?=:.*)\")\n\n# after\nlabel_replace(up, \"d\", \"$1\", \"instance\", \"([^:]+):.*\")","handlingStrategy":"validation","validationCode":"// Go/RE2 pre-check before sending the query\nif _, err := regexp.Compile(\"^(?s:\" + regexStr + \")$\"); err != nil { return fmt.Errorf(\"bad regex: %w\", err); }","typeGuard":null,"tryCatchPattern":null,"preventionTips":["Test label_replace regexes with Go's regexp package (RE2): no lookaheads, no backreferences","Double-check escaping when embedding regex in YAML rules","Validate dynamically assembled regexes before query submission"],"tags":["promql","label-replace","regex","re2","go"],"backgroundTag":null,"analyzedSha":"44d6a0e0b1dbdcba4e68853d50e0bafc87d90507","analyzedAt":"2026-08-15T08:44:33.427Z","schemaVersion":2},"datasetVersion":"2026-08-15T17:31:12.345Z"}