I need to match an alphanumeric word. It can contain “-” but not at the end or start, and “-” must not be repeated (like “–“) and the word length must be between 2 and 24 characters.
some examples:
adfg
asd-asdasd
asd-asd-asd
and these should not be matched:
-asd
asd-
-asd-
-asd--asd-
One of the most difficult things about using regexes is resisting the lure of excessive cleverness. You’ve got two separate, incompatible tests to perform. Length:
…and composition:
While it might be possible to come up with a regex that will perform both tests in one pass, there’s no need. Just do one of them as a lookahead: