-3

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?

Cœur
  • 32,421
  • 21
  • 173
  • 232
user3736648
  • 6,783
  • 17
  • 67
  • 145

3 Answers3

0

You could use the below simple regex which uses negative lookahead assertion.

^(?!-|.*-$|.*-[\W_]|.*[\W_]-).*$

DEMO

.*-[\W_]|.*[\W_]- part in the negative lookahead assertion ensures that the - isn't preceded nor followed by a non-word character or _ symbol.

Avinash Raj
  • 160,498
  • 22
  • 182
  • 229
0
^(?!(?:.*-(?=$|-))|-).*$

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 -.

vks
  • 63,206
  • 9
  • 78
  • 110
0

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])[^-]+?)*$"

DEMO

If only letters, digits and dashes are allowed, it is even simpler:

@"^[\da-z]+(?:-[\da-z]+)*$"

DEMO

Alex Skalozub
  • 2,341
  • 12
  • 13