Search code examples
javascriptregexmaxlength

Javascript RegEx - Enforcing two max-lengths


It's been a while that I am juggling around this. Hope you can give me some pointers.

All I want to achieve is, the string should contain EXACTLY 4 '-' and 10 digits in any giver order.

I created this regex : ^(-\d-){10}$ It does enforce max-length of 10 on digits but I am not getting a way to implement max-length of 4 for '-'

Thanks


Solution

  • Ok, here's a pattern:

    ^(?=(?:\d*?-){4}\d*$)(?=(?:-*?\d){10}-*$).{14}$
    

    Demo

    Explanation:

    • The main part is ^.{14}$ which simply checks there are 14 characters in the string.

    • Then, there are two lookaheads at the start:

      • (?=(?:\d*?-){4}\d*$)
      • (?=(?:-*?\d){10}-*$)

      The first one checks the hyphens, and the second one checks the digits and make sure the count is correct. Both match the entire input string and are very similar so let's just take a look at the first one.

      • (?:\d*?-){4} matches any number of digits (or none) followed by a hyphen, four times. After this match, we know there are four hyphens. (I used an ungreedy quantifier (*?) just to prevent useless backtracking, as an optimization)
      • \d*$ just makes sure the rest of the string is only made of digits.