Julian Day Regex Without Leading Zeros

514 views Asked by At

I am really struggling with creating a Reg Ex for Julian Day that does not allow leading zeros.

I am using it for Input Validation using JavaScript Reg Ex. It needs to match 1 through 366.

Example Matches:

  • 1
  • 99
  • 366
  • 159

Example Match Failures:

  • 01
  • 001
  • 099
  • 367
  • 999
  • 0

I tried this on regex101:

^[1-9]|[1-9][0-9]|[1-3][0-5][0-9]|36[0-6]$

But for I am not getting the optional parts down right. So when I put in 266, I get a match on 2 and 66. (This issue is translating to my input validation control.)

I thought about trying to use + for one or more, but I need to not allow leading zeros, so that does not work.

I have read the guidance on asking a RegEx question and tried to follow it, but if I missed something, please let me know and I will update my question.

1

There are 1 answers

0
Wiktor Stribiżew On BEST ANSWER

The main issues are two: 1) the alternatives should have been grouped so that ^ and $ anchors could be applied to all of them, 2) the [1-3][0-5][0-9] part did not match 160 to 199 and 260 to 299, this part should have been split into two separate branches, [12][0-9]{2}|3[0-5][0-9].

You may use

^(?:[1-9]|[1-9][0-9]|[12][0-9]{2}|3[0-5][0-9]|36[0-6])$

See the regex demo.

Details

  • ^ - start of string
  • (?: - group of alternatives:
    • [1-9] - 1 to 9
    • | - or
    • [1-9][0-9] - 10 to 99
    • | - or
    • [12][0-9]{2} - 100 to 299
    • | - or
    • 3[0-5][0-9] - 300 to 359
    • | - or
    • 36[0-6] - 360 to 366
  • ) - end of the alternation group
  • $ - and the end of the string.