I want to code a regular expression pattern that needs to check the following:
Every dash (-) character must be immediately preceded and followed by a letter or number; consecutive dashes are not permitted.
How to do this?
I want to code a regular expression pattern that needs to check the following:
Every dash (-) character must be immediately preceded and followed by a letter or number; consecutive dashes are not permitted.
How to do this?
You could use the below simple regex which uses negative lookahead assertion.
^(?!-|.*-$|.*-[\W_]|.*[\W_]-).*$
.*-[\W_]|.*[\W_]-
part in the negative lookahead assertion ensures that the -
isn't preceded nor followed by a non-word character or _
symbol.
^(?!(?:.*-(?=$|-))|-).*$
Try this.See demo.
https://regex101.com/r/aZ6zX0/4
This uses negative lookahead
to make sure -
is not followed by -
or $
and does not start with -
.
We only know every dash should be surrounded with letters or digits, but we have no clue if the whole string is limited to letters, digits and dashes. Also it was not specified if string is required to contain dashes at all.
Assuming @#$abc-def#%
is a valid string, we need to go with something like:
@"^[^-]+?(?:(?<=[\da-z])-(?=[\da-z])[^-]+?)*$"
If only letters, digits and dashes are allowed, it is even simpler:
@"^[\da-z]+(?:-[\da-z]+)*$"