Regular expression limit length of character while not matching last character of string

Viewed 123

I'm working on a new regex to prepare for a host-name on a virtual machine, however, I'm running into issue on how to limit character length of 24 while making sure the last character is not a dot or a minus. (the first character must be an alpha character)

I have gotten as far as making sure the first character is an alpha. The second group of characters are 23 in length with [a-zA-z0-9] including the dot and minus. I've tried the negative look-behind .+(?<!-|\.)$ in addition but does not work.

^[a-zA-Z]([a-zA-Z0-9-.]{0,23}

I expect the output of a123456789012345678911234 to be correct already. I expect this output should be incorrect a12345678901234567891123-

2 Answers

You may use

^[a-zA-Z](?:[a-zA-Z0-9.-]{0,22}[a-zA-Z0-9])?$

See the regex demo and the regex graph:

enter image description here

Details

  • ^ - start of string
  • [a-zA-Z] - a letter
  • (?:[a-zA-Z0-9.-]{0,22}[a-zA-Z0-9])? - an optional sequence of:
    • [a-zA-Z0-9.-]{0,22} - 0 to 22 letters, digits, . or - chars
    • [a-zA-Z0-9] - a letter or digit
  • $ - end of string.

In order to limit the number of characters, the expression must be enclosed in ^ and $ denoting the beginning and the end.

     ^[a-zA-Z][a-zA-Z0-9.-]{0,22}[a-zA-Z0-9]$

[] defines one character from those in parentheses {a, b} defines the number of occurrences of the preceding character from 0 to 22 in the example a total limit of 2 to 24 characters

This can be saved shorter but in this way it is the easiest to understand.

Related