tags:

views:

128

answers:

3

I have a need of checking whether there is the date in the string or not.

FUTIDX 26FEB2009 NIFTY 0 -- There is date in the string.

FUTIDX MINIFTY 30 Jul 2009 -- There is date in the string.

FUTSTK ONGC 27 Mar 2008 -- There is date in the string.

How can I do that ?

A: 

You can use the DateTime.TryParse() Method. But before you need to clean your string from the trash characters.

Another way is to write your own parser with custom rules of expressions.

KroaX
@KroaX,Trash Character ?
Harikrishna
@Harikrishna: I think he means removing everything but the date itself. But, if you were able to do that, then I don't think you would be asking your question.
dboarman
@dboarman-Yes it is.
Harikrishna
A: 

What are all the formats you are supporting? Depending on that you will need a parser or maybe a regular expression (depending on the formats) to get the date out.

Edit: So it always will be DD MON YYYY or DDMONYYYY. Just have a regular expression to filter this part out from string and it would work.

Check this expression. A bit of modifications and it will work.

danish
+1  A: 

What @danish is telling you is that you will need to try out RegEx (or regular expressions). There are tons of sites out there - MSDN; Practical Parsing; Learn Regular Expressions - just to name a few.

If you are expecting your date in only 2 specific formats, then we only have 2 patterns that we would need to match. Your example data:

FUTIDX 26FEB2009 NIFTY 0 -- There is date in the string.

FUTIDX MINIFTY 30 Jul 2009 -- There is date in the string.

FUTSTK ONGC 27 Mar 2008 -- There is date in the string.

provides us with 2 patterns:

  1. ddMMMyyyy
  2. dd Mmm yyyy

The example below will only look for a month in the short form. This should be enough to help you get going.

using System;
using System.Text.RegularExpressions;

namespace regexmonthtest
{
    class MainClass
    {

            // in your class, define 2 string patterns
        static string pattern = @"(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)";

        public static void Main (string[] args)
        {
            Console.WriteLine (HasDate("FUTIDX 26FEB2009 NIFTY 0"));
            Console.WriteLine (HasDate("FUTSTK MINIFTY 30 Jul 2009"));
            Console.WriteLine (HasDate("FUTIDX 26api1234 NIFTY 0"));
        }


        public static bool HasDate (string textIn)
        {
            textIn = textIn.ToLower();
            Console.Write(textIn + '\t');

            return (Regex.Match(textIn, pattern).Success);
        }
    }
}

output:

futidx 26feb2009 nifty 0 True
futstk minifty 30 jul 2009 True
futidx 26api1234 nifty 0 False

dboarman
@dboarman,Thanks sir...
Harikrishna