-3

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

  • 1
    Integer or decimal? Why regex and not just a numeric comparison which will be more efficient and accurate? – Jon P Mar 22 '21 at 03:51
  • Integer. It's Regex because i am keeping the expression in a json and using later on code . – Sk Azharuddin Mar 22 '21 at 04:00
  • Personally, I'd store min and max valid values in the json rather than an unwieldy regex. Much simpler when you want to change that range – Jon P Mar 22 '21 at 04:50

1 Answers1

0

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);
           }
        }
        
    }
}
Rex Henderson
  • 412
  • 2
  • 7