Search code examples
c#.netregexqregularexpression

Regular expression for value Range from 1 - 1440 (Integer)


What will be the regular expression for value Range from 1 - 1440? (Integer)


Solution

  • I think this will do it. I'm running tests. I'm acting under the assumption you will not have numbers padded with zero like "0999"

    "^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1[0-3][0-9][0-9]|14[0-3][0-9]|1440)$"

    breakdown:
    [1-9]   obvious
    [1-9[0-9]  allow 10 to 19
    [1-9][0-9][0-9] allow 100 to 199
    1[0-3][0-9][0-9] allow 1000 to 1399
    14[0-3][0-9] allow 1400 to 1439
    1440         obvious
    

    Appears to work:

    using System;
    using System.Text.RegularExpressions;
    
    public class Program
    {
        public static void Main()
        {
            
            for(int i = 0;i < 10000;i++)
            {
                
               if(Regex.IsMatch(i.ToString(),"^([1-9]|[1-9][0-9]|[1-9][0-9][0-9]|1[0-3][0-9][0-9]|14[0-3][0-9]|1440)$"))
               {
                   Console.WriteLine(i);
               }
            }
            
        }
    }