Minimum length in regular expression

Viewed 2269

I am well aware that to indicate a minimum length for a regular expression one should use this quantifier, if a min of say 4 characters is wanted {4,}

I am trying to compile a regex in go that will allow

  • a min of 4 chars in total, including the hyphen

  • only letters digits and hyphens

  • last character should not be a hyphen

So it was suggested that I use this:

^[a-zA-Z0-9-]*[a-zA-Z0-9]$

which seems to do the job.

Now, given that I want to enforce a min of 4 chars, I modified it a bit as follows:

^[a-zA-Z0-9-]*[a-zA-Z0-9]{4,}$

However this does not seem to do the work given that the pattern below

eee0-lll

does not match (according to my requirements it should).

One of the constraints I am faced with is that go does not allow for lookaround assertions.

1 Answers

You can use

^[a-zA-Z0-9-]{4,}\b$

See the regex demo

Details

  • ^ - start of string
  • [a-zA-Z0-9-]{4,} - four or more ASCII letters, digits or hyphens -\b - a word boundary that requires a word char (letter, digit or _) to appear immediately to the left of the current position because the next pattern requires...
  • $ - end of string.
Related