Home > front end >  Regex for exactly number of chars in random order
Regex for exactly number of chars in random order

Time:05-27

I have a regex that accepts 8-10 chars: only # and - (in random order)

^[-#]{8,10}$

But I need exactly 8 of # and 0-2 of -

For example, proper strings are:

-########-
########
##-###-###

Regex

^[#]{8}[-][0,2]$

It doesn't work cause accepts only 8 of# and some of - in this particular order

CodePudding user response:

You can assert 8-10 chars, and match 8 # chars surrounded by optional - chars

^(?=.{8,10}$)(?:-*#){8}-*$

Explanation

  • ^ Start of string
  • (?=.{8,10}$) Positive lookahead to assert 8 - 10 characters in total
  • (?:-*#){8} Match 8 times optional - and then #
  • -* Match optional trailing -
  • $ End of string

See a regex demo.

  • Related