I am currently trying to formulate a regex validation to identify a word with alphanumberic start and end characters, however the letters inbetween can be of special characters '.', '-' or '_'. This is a validation for kube labels.
Valid label value:
must be 63 characters or less (can be empty),
unless empty, must begin and end with an alphanumeric character ([a-z0-9A-Z]),
could contain dashes (-), underscores (_), dots (.), and alphanumerics between.
Right now I am at ^([A-Za-z0-9][A-Za-z0-9.\-_] )[A-Za-z0-9]$
This seems to work for most strings, however if I have a single character alphanumeric string, this fails. Can someone help me formulate the right regex pattern.
Test Strings:
- a234.b
- 1
- a
- 1.-2
- 12ab
- 2_2
CodePudding user response:
Try this:
^([A-Za-z0-9][\w.-]{0,61})?[A-Za-z0-9]$|^$
Notes:
\w==A-Za-z0-9_^...$|^$permits empty{0,61}limits the max non-end chars to 61, for an overall max length of 63
CodePudding user response:
A succinct version of the regex answered by Wiktor would be ^(?:[A-z\d][A-z\d._\-]*)?[A-z\d]$
