Regex to disallow more than 1 dash consecutively

^[A-Za-z0-9]+(-[A-Za-z0-9]+)*$

Using this regular expression, the hyphen is only matched just inside the group. This hyphen has the [A-Za-z0-9]+ sub-expression appearing on each side. Because this sub-expression matches on one or more alpha numeric characters, its not possible for a hyphen to match at the start, end or next to another hyphen.


^(?!-)(?!.*--)[A-Za-z0-9-]+(?<!-)$

Explanation:

^             # Anchor at start of string
(?!-)         # Assert that the first character isn't a -
(?!.*--)      # Assert that there are no -- present anywhere
[A-Za-z0-9-]+ # Match one or more allowed characters
(?<!-)        # Assert that the last one isn't a -
$             # Anchor at end of string

Tags:

Regex