Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Regular Expressions in .NET

, 17 Dec 2005 CPOL
Introduction to regular expressions and how to use them in .NET
regex_dotnet_demo.zip
App.ico
TimeParserRegEx.csproj.user
using System;
using System.Text.RegularExpressions;

namespace TimeParserRegEx
{
	/// <summary>
	/// Summary description for Class1.
	/// </summary>
	class FreeFormTimeParser
	{
		/// <summary>
		/// The main entry point for the application.
		/// </summary>
		[STAThread]
		static void Main(string[] args)
		{
			try 
			{
				System.Console.WriteLine ("Enter time to be parsed: ");
				string inputStr = System.Console.ReadLine ();
				DateTime parsedTime = FreeFormTimeParser.ParseTime (inputStr);

				System.Console.WriteLine ("The parsed time in long notation is: " 
					+ parsedTime.ToLongTimeString());
			} 
			catch (FormatException e) 
			{
				System.Console.WriteLine ("Invalid time format");
			}
		}

		private const string TIME_STR = 
			@"^\s?(?<time>"
			+ @"(?<hour>\d{1,2})"
			+ @"(:(?<min>\d{1,2}))?"
			+ @"\s?((?<am_pm>(am|pm)))?"
			+ @")\s?$";

		private static int ConvertAmPm (string amPm, int hour)
		{
			int retHour = hour;

			amPm = amPm.ToLower();
			if (amPm.Equals("am")) 
			{
				// all hours remain the same except the 12:00 am (which is 0000 hours)
				if (hour == 12)
					retHour = 00;
			}
			else if (amPm.Equals("pm")) 
			{
				// add 12 to hours except if 12:00 pm
				if (hour != 12)
					retHour = hour + 12;
			}
			else
				throw new FormatException ("Invalid amPm flag format");

			return retHour;
		}

		static DateTime ParseTime (string strTime)
		{
			DateTime currTime = DateTime.Now;
			DateTime finalTime = DateTime.Today;
			Match m;
			int hour = 0,
				min = 0;

			Regex regExTime = new Regex (TIME_STR, 
				RegexOptions.IgnoreCase
				| RegexOptions.CultureInvariant
				| RegexOptions.IgnorePatternWhitespace
				| RegexOptions.Compiled);

			m = regExTime.Match (strTime);
			if (m.Success)
			{
				if (m.Groups["hour"].Success)
					hour = Int32.Parse (m.Groups["hour"].Value);
				if (m.Groups["min"].Success)
					min = Int32.Parse (m.Groups["min"].Value);
				if (m.Groups["am_pm"].Success) 
				{
					hour = ConvertAmPm (m.Groups["am_pm"].Value, hour);
				}
			} 
			else
				throw new FormatException ("Invalid time format");

			if (hour > 23 || min > 59)
				throw new FormatException ("Invalid time format");

			finalTime = new DateTime (currTime.Year, currTime.Month, currTime.Day,
				hour, min, 0);

			return finalTime;
		}
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ovais Ahmad Khan
Web Developer
Hong Kong Hong Kong
Ovais Khan is a Software Engineer at Kalsoft (Pvt.) Ltd, where he is working on C# and C++ projects for clients in Pakistan and UAE.
 
He has done MS (Computer Science). For more details please visit Ovais Khan 's home page and his blog

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150129.1 | Last Updated 17 Dec 2005
Article Copyright 2005 by Ovais Ahmad Khan
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid