Barrie Anderson
Barrie Anderson

Reputation: 23

Regex returning no matches for this syntax

I was wondering if you could advise, i have scoured mostly your site for similar examples but as programmers your answers seem very complex to someone like me who is a beginner to this sort of thing

Basically we have a file name structure which has a minimum of 5 characters and a maximum of 6 and starts with either 1 or 2, then preceded by a full stop . then only a number between 1 and 5 after the .

An example file name is is below

123456.1

I am trying to create a regex which will pick out the correct filename as per the statement above when ran against a text file list, however i have tried this and it does not work

If I try without 1|2 it picks up the reference but I need the first digit to be 1 or 2

^1|2\d{5,6}][\.][0-5]{1}$

Hoping for this to pick out from a text file any digit that starts with a 1 or 2 and minimum of 5 and max of 6 digits with a full stop after then followed by another number

Basically some examples i want it to pick out are below:

123456.1  OK
25689.2   OK
061589.2  NOT OK
1235.6    NOT OK
765812.1  NOT OK
289657.5  OK

I hope i have provided enough info, let me know if not.

Upvotes: 1

Views: 57

Answers (2)

Reacher Gilt
Reacher Gilt

Reputation: 1813

If you're actually validating numbers, why not actually validate numbers? (This answer may be slightly stunty)

  class Program
    {
        private static readonly string[] Items =
        {
            "123456.1",
            "25689.2",
            "061589.2", //NOT
            "1235.6", //NOT
            "765812.1", //NOT
            "289657.5"
        };
        static void Main()
        {
             foreach (string item in Items)
             {
                 Console.WriteLine(Validate(item));
             }
            Console.ReadKey();
        }
        static bool Validate (string item)
        {
            decimal d;
            if (decimal.TryParse(item,out d))
            {
                if (((d < 10000.1m) || (d > 299999.5m)) ||
                    ((d > 29999.5m) &&  (d < 100000.1m))) return false;
                // validate fraction here
                var i = d - decimal.Truncate(d);
                return (i >= 0.1m && i <= 0.5m);
            } 
            return false;
        }
    }

Upvotes: 0

speakr
speakr

Reputation: 4209

^[12]\d{4,5}\.[1-5]$ should work.

Short explanation:

  • [12] matches either a 1 or a 2
  • \d{4,5} matches any sequence of (any) digits with a length of min 4 and max 5 (because we already matched the first digit with [12] before)
  • \. matches a period
  • [1-5] matches any digit between 1 and 5

Upvotes: 3

Related Questions