user3751248
user3751248

Reputation: 323

Check if a number in a string contains a valid year in c#

I have a the following string and need to ensure that the number in the string is a valid year. So in this case 2014.

var notesField = "Payment for the month ending 30 Nov 2014";
char[] whitespace = new char[] { ' ', '\t' };
string[] text = notesField.Split(
                          whitespace,
                          StringSplitOptions.RemoveEmptyEntries
                          );

Upvotes: 1

Views: 4616

Answers (2)

Justin
Justin

Reputation: 86779

You can't - any positive integer is (in theory) a potentially valid year. You need to come up with a sensible definition of "what a valid year", an example might be "a 4 digit number between 2005 and 2020" (e.g. if you only expect to see dates in the recent past or near future).

This of course doesn't handle the "Bob gave Alice 2014 cows" case - to fix this you could try to be clever and do some basic date parsing (e.g. recognising the "30 Nov" part of your string), however in general this is a hard problem to solve - consider what could happen if your system came across someone called "June"?

The best way to handle this is to place restrictions on your input to make validation easier. Ideally you would provide a separate control specifically for entering dates, however if you are for some reason stuck with text input you could just look for strings of the form "Payment for the month ending {Day} {Month} {Year}" - the more relaxed you are with the input you expect the harder time you are going to have trying to parse & validate it.

Upvotes: 4

Jenish Rabadiya
Jenish Rabadiya

Reputation: 6766

The approach to find or validate year in this way is never recommended but if you are sure that there will be exactly one four digits word in the sentence then you can use regex match like below.

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        Regex regex = new Regex(@"\d{4}");
        Match match = regex.Match("Payment for the month ending 30 Nov 2014");
        if (match.Success)
        {
            Console.WriteLine(match.Value);
        }
    }
}

working fiddle is here

Upvotes: 3

Related Questions