Regex for 23:46

Hi,

I need to check if a string in a certain format using Regular Expression.

I want to check if the string is

23:46

format.

where 23 can be any 2-digit integer and 46 can be any 2-digit integer as well..and the two integers are separated by a colon character :

How can I write it in a regular expression

Thanks



Answer this question

Regex for 23:46

  • Bob Alston

    I don't know if this is precise enough for you, but here is how you get started:

    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Text.RegularExpressions;

    namespace RegExTest
    {
    class Program
    {
    static void Main(string[] args)
    {
    Match M;
    String timePattern = @"(\d)(\d):(\d)(\d)"; // our pattern ##:##


    String seeIfThisMatches = "23:46";
    String seeIfThisMatches2 = "254:2";

    // test the first string
    M = Regex.Match(seeIfThisMatches, timePattern);

    // see what our outcome was
    if (M.Success)
    Console.WriteLine("First Expression matches.");
    else
    Console.WriteLine("First Expression does NOT match");



    // test the second string
    M = Regex.Match(seeIfThisMatches2, timePattern);

    if (M.Success)
    Console.WriteLine("Second Expression matches.");
    else
    Console.WriteLine("Second Expression does NOT match");

    }
    }
    }


    The output is:

    First Expression matches.
    Second Expression does NOT match
    Press any key to continue . . .


    Rob K


  • SivaS

    Actually when I think about this, you better compare for both cases, and if you find a match, use the MatchCollection to finally pull out your string. ... but I think you are going to need to use 2 different pattern matches (1 for time with single : and another for the expression with 2 :'s... there's probably a clever way to merge them into one regular expression and if there is, it might be kinda tuff to read or change later).

    Rob K



  • DragonsBlade

    Great, thanks a lot..There is one small thing though...

    Say if,

    String seeIfThisMatches = "2/2/1900 3:00:00 AM";

    String seeIfThisMatches2 = "25:42";

    and I want to extract @"(\d)(\d):(\d)(\d" part from both using a single regular expression, how would I be able to do that

    Thanks,


  • Visagar

    I changed the match string to include 1 space in front and back of the expression... it should be a little more precise:

    Match M;
    String timePattern = @"(\s)(\d)(\d):(\d)(\d)(\s)"; // our pattern ##:##

    MatchCollection extracted = Regex.Matches(seeIfThisMatches, timePattern);
    Console.WriteLine("Extracted time from 1st string: " + extracted[0]); // notice that extracted is like an array

    I like to use this as a reference document for regular expressions:
    http://www.windowsdevcenter.com/pub/a/oreilly/windows/news/csharp_0101.html

    Enjoy!

    Rob K

  • Regex for 23:46