atul atul - 3 months ago 14
Javascript Question

Regular expression for area id in networking

Require regular expression for the following format

Rules:


  1. Allowed values integer
    [0-9]
    , alphabet
    [a-f]
    or
    [A-F]

  2. Each group can be max of 2 digit and each group should be
    separated by a space

  3. There can be max 13 such groups



Input


  1. 3F 22 11 3F 22 11 3F 22 11 3F 22 11 3F 22 11 (wrong)

  2. 49 00 01 (True)

  3. 23 (True)

  4. 3F 22 11 3F 22 11 3F 22 11 3F 22 11 3F (true)



I tried this but no luck

([0-9a-fA-F]{2} (\s){1,13}

Answer

The problem with ([0-9a-fA-F]{2} (\s){1,13} is that it does not have anchors and the parentheses are not paired. Also, (\s){1,13} means match 1 to 13 whitespaces. Definitely not what you need.

You can use the following regex:

/^[0-9a-f]{2}(?: [0-9a-f]{2}){0,12}$/i

See the regex demo

Pattern details:

  • ^ - start of string anchor
  • [0-9a-f]{2} - 2 characters from the set - a digit or hex letter
  • (?: [0-9a-f]{2}){0,12} - 0 to 12 sequences of:
    • - a space (you may use \s here to match any whitespace)
    • [0-9a-f]{2} - 2 characters from the set - a digit or hex letter
  • $ - end of string.

The /i is a case insensitive modifier that lets you use [a-f] to match A, B, C, D, E and F, too.