Search code examples
regexnumbersexpression

Regex to accept numbers and/or number range separated by commas, but between range 1-64


I need to validate a string entered by user. The string should allow numbers or ranges, separated by comma. The numbers must be between 1 and 64.

Sample: 1,8,7-9,10-12,20-45

A space is allowed before and after a comma or '-'.


Solution

  • Here you go,

    ^(?:6[0-4]|[1-5]\d|[1-9])(?: *- *(?:6[0-4]|[1-5]\d|[1-9]))?(?: *, *(?:6[0-4]|[1-5]\d|[1-9])(?: *- *(?:6[0-4]|[1-5]\d|[1-9]))?)*$
    

    I used <space>* instead of \s* because \s matches newline characters also. Use \s instead of a space, if you have no problem about newline character. Use \s? instead of <space>*, if you want to allow an optional space not zero or more spaces.

    DEMO