skip to Main Content

I want to create a regex that accepts a string like following:

DXXX HH:mm

where XXX is a number from 1 to 999 but it can also accept 0 prefixed numbers like 01 and 001, but it cannot accept for example 0001 where the total length > 3

HH:mm is the hour and minute in 24h format.

Example for accepted values: D001 14:01 and D999 00:00

I have wrote the second part which is : /^(2[0-3]|[0-1][d]):[0-5][d]$/

And for the first part: ^d{1,3}$ but this accepts 0, 00 and 000.

How can I solve this ?

2

Answers


  1. const regex = /^D(?:0d?[1-9]|[1-9]{1,3}) [0-2]d:[0-5]d$/
    
    console.log(regex.test("D001 14:01"))
    console.log(regex.test("D999 00:00"))
    console.log(regex.test("D000 00:00"))
    console.log(regex.test("D00 00:00"))
    console.log(regex.test("D0 00:00"))
    console.log(regex.test("D001 00:00"))
    console.log(regex.test("D01 00:00"))
    console.log(regex.test("D011 00:00"))
    Login or Signup to reply.
  2. Let’s keep it simple:

    re = String.raw`
        ^
        D
        (                          # numeric group
            [1-9] [0-9]? [0-9]?    # 1 or 12 or 123
            |                      # or
            0 [1-9] [0-9]?         # 01 or 012
            |                      # or
            00 [1-9]               # 001
        )
        x20  # space
        (                    # hours
            2 [0-3]          # 20..23      
            |                # or
            [0-1] [0-9]      # 00...19
        )
        :
        (                    # seconds
            [0-5] [0-9]      # from 00 to 59
        )
        $
    `
    
    re = new RegExp(re.replace(/#.*|s+/g, ''))
    
    console.log(re)
    
    console.log(re.test('D001 23:11'))
    console.log(re.test('D011 23:11'))
    console.log(re.test('D111 23:11'))
    
    console.log(re.test('D0 23:11'))
    console.log(re.test('D00 23:11'))
    console.log(re.test('D000 23:11'))
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search