Umer Waheed
Umer Waheed

Reputation: 4594

How to make regex of 0-272

I want to make regex from 0-272. I made this but its not working properly.

^([0-9]|[0-9][0-9]|[0-9][0-9][0-2])$

This accept 270,272,102 but not accept 103 and 104. How can i make it?

Upvotes: 1

Views: 56

Answers (2)

abc123
abc123

Reputation: 18823

Regex

^(\d|\d\d|[01][0-9][0-9]|2[0-6][0-9]|27[0-2])$

Regular expression visualization

Debuggex Demo

Description

^ assert position at start of a line
1st Capturing group (\d|\d\d|[01][0-9][0-9]|2[0-6][0-9]|27[0-2])
    1st Alternative: \d
        \d match a digit [0-9]
    2nd Alternative: \d\d
        \d match a digit [0-9]
        \d match a digit [0-9]
    3rd Alternative: [01][0-9][0-9]
        [01] match a single character present in the list below
            01 a single character in the list 01 literally
        [0-9] match a single character present in the list below
            0-9 a single character in the range between 0 and 9
        [0-9] match a single character present in the list below
            0-9 a single character in the range between 0 and 9
    4th Alternative: 2[0-6][0-9]
        2 matches the character 2 literally
        [0-6] match a single character present in the list below
            0-6 a single character in the range between 0 and 6
        [0-9] match a single character present in the list below
            0-9 a single character in the range between 0 and 9
    5th Alternative: 27[0-2]
        27 matches the characters 27 literally
        [0-2] match a single character present in the list below
            0-2 a single character in the range between 0 and 2
$ assert position at end of a line

Upvotes: 1

Mureinik
Mureinik

Reputation: 311978

As I noted in the comments, I don't think this is a good usecase for a regex. But if that's the requirement it could be done. Let's break it up to usecaes:

  • Any 1 digit number
  • Any 2 digit number
  • Any three digit number with a 1 hundreds digits
  • Any three digit number with a 2 hundreds digits and a tens digit of 0-6
  • Any three digit number with a 2 hundreds digits, a tens digit of 7 and a ones digit of 0-2:

So if we express this as a regex:

^([0-9]|[0-9][0-9]|1[0-9][0-9]|2[0-6][0-9]|27[0-2])$

Upvotes: 3

Related Questions