SQL and Java Learner SQL and Java Learner - 2 months ago 12
C# Question

C# Regex expression to match numbers, hyphens, colons, spaces and commas

I haven't used regex before so if anyone could lend a hand that would be awesome.
I have text similar to this:

2016-09-16 14:25:28,756

stored in a string. I want to create a regex to see if what was entered contains numbers, hyphens, colons, spaces and commas. What would be the regular expression for this? Also, would there be a way to compare the string to a specific order of a regex? For example, if someone enters:

2012-10-18 15:29:37,886

this would be correct because the form is

####(hyphen)##(hyphen)## (space) ##(colon)##(colon)##(comma)###

Answer

If you want an exact match to the text you have, I would use:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        Regex regex = new Regex(@"\d{4}[-]\d{2}[-]\d{2}[ ]\d{2}[:]\d{2}[:]\d{2}[,]\d{3}");
        Match match = regex.Match("2012-10-18 15:29:37,886");
        if (match.Success)
        {
            Console.WriteLine("The value is a match.");
        }
    }
}

A great resource for validating and testing regular expressions is: http://regexr.com/