1818 */
1919public class PrometheusNaming {
2020
21+ /**
22+ * @deprecated Not used anymore. Kept for backward compatibility. The validation is now done
23+ * without regex for better performance.
24+ */
25+ @ Deprecated
26+ @ SuppressWarnings ("UnusedVariable" )
2127 private static final Pattern METRIC_NAME_PATTERN = Pattern .compile ("^[a-zA-Z_:][a-zA-Z0-9_:]*$" );
2228
23- /** Legal characters for label names. */
29+ /**
30+ * Legal characters for label names.
31+ *
32+ * @deprecated Not used anymore. Kept for backward compatibility. The validation is now done
33+ * without regex for better performance.
34+ */
35+ @ Deprecated
36+ @ SuppressWarnings ("UnusedVariable" )
2437 private static final Pattern LEGACY_LABEL_NAME_PATTERN =
2538 Pattern .compile ("^[a-zA-Z_][a-zA-Z0-9_]*$" );
2639
@@ -90,7 +103,29 @@ public static String validateMetricName(String name) {
90103 }
91104
92105 public static boolean isValidLegacyMetricName (String name ) {
93- return METRIC_NAME_PATTERN .matcher (name ).matches ();
106+ if (name .isEmpty ()) {
107+ return false ;
108+ }
109+ // First character must be [a-zA-Z_:]
110+ char first = name .charAt (0 );
111+ if (!((first >= 'a' && first <= 'z' )
112+ || (first >= 'A' && first <= 'Z' )
113+ || first == '_'
114+ || first == ':' )) {
115+ return false ;
116+ }
117+ // Remaining characters must be [a-zA-Z0-9_:]
118+ for (int i = 1 ; i < name .length (); i ++) {
119+ char c = name .charAt (i );
120+ if (!((c >= 'a' && c <= 'z' )
121+ || (c >= 'A' && c <= 'Z' )
122+ || (c >= '0' && c <= '9' )
123+ || c == '_'
124+ || c == ':' )) {
125+ return false ;
126+ }
127+ }
128+ return true ;
94129 }
95130
96131 public static boolean isValidLabelName (String name ) {
@@ -106,7 +141,25 @@ private static boolean isValidUtf8(String name) {
106141 }
107142
108143 public static boolean isValidLegacyLabelName (String name ) {
109- return LEGACY_LABEL_NAME_PATTERN .matcher (name ).matches ();
144+ if (name .isEmpty ()) {
145+ return false ;
146+ }
147+ // First character must be [a-zA-Z_]
148+ char first = name .charAt (0 );
149+ if (!((first >= 'a' && first <= 'z' ) || (first >= 'A' && first <= 'Z' ) || first == '_' )) {
150+ return false ;
151+ }
152+ // Remaining characters must be [a-zA-Z0-9_]
153+ for (int i = 1 ; i < name .length (); i ++) {
154+ char c = name .charAt (i );
155+ if (!((c >= 'a' && c <= 'z' )
156+ || (c >= 'A' && c <= 'Z' )
157+ || (c >= '0' && c <= '9' )
158+ || c == '_' )) {
159+ return false ;
160+ }
161+ }
162+ return true ;
110163 }
111164
112165 /**
0 commit comments