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

Regex for 23:46
Bob Alston
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
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
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