I am trying to validate the format of date and also validate the date equal to or less than today in C# I am trying to achieve this in c# using regular expressions.
The formats I am trying to support are dd/mm/yyyy, dd-mm-yyyy, yyyy-mm-dd, yyyy/mm/dd.
var expressions = new List<Regex>();
expressions.Add(new Regex("^\\d{4}-((0\\d)|(1[012]))-(([012]\\d)|3[01])$"));
expressions.Add(new Regex("(((0|1)[1-9]|2[1-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"));
return expressions;
Can somone please tell me what i am doing wrong in my reg ex and also suggest a better way to achieve this.
There is no need to use regular expressions for this; you can call DateTime.ParseExact or DateTime.TryParseExact with the permitted formats as an argument. Unlike regular expressions, this approach will also ensure that the user-provided date is valid (e.g., allowing "2016-02-29" but not "2015-02-29").
string inputDate = "2015-01-01";
DateTime dt;
bool validDate = DateTime.TryParseExact(inputDate,
new[] { "dd/MM/yyyy", "dd-MM-yyyy", "yyyy-MM-dd", "yyyy/MM/dd" },
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out dt);
Console.WriteLine(validDate ? dt.ToString("MM/dd/yyyy") : "Invalid date"); // 01/01/2015
There are a couple of problems here.
Your regular expression here
"^\\d{4}-((0\\d)|(1[012]))-(([012]\\d)|3[01])$"
Can only find date format with -, not with / (that is 1999-12-25 is valid but 1997/11/15 is not). If you want to change it, you should use
"\\d{4}(-|\/)((0\\d)|(1[012]))(-|\/)(([012]\\d)|3[01])$" //^ removed, \/ added
Which would match both 1999-12-25 and 1997/11/15 (edit: but will also match 1998/05-28!)
Likewise, your regular expression here
"(((0|1)[1-9]|2[1-9]|3[0-1])\\/(0[1-9]|1[0-2])\\/((19|20)\\d\\d))$"
Can only match 12/11/1954 but cannot match 12-11-1954. Some more, because you put (0|1)[1-9]|2[1-9], your regex cannot match 10-11-1954. Use
"((0|1)[0-9]|2[0-9]|3[0-1])(-|\/)(0[1-9]|1[0-2])(-|\/)(19|20)\\d\\d$"
instead
But seriously, unless is a must, it is a hellish task to parse (not to say to compare) DateTime value with Regex! You should just use DateTime.TryParse or DateTime.Parse together with TimeSpan for parsing and for comparison respectively.
Related
I was looking in the Microsoft doc's and I can't find any explanation why ParseExact doesn't understand my date.
Could somebody explain why this code throws an exception?
DateTime.ParseExact("6092019", "dMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None)
From the docs: DateTime.ParseExact Method
If format is a custom format pattern that does not include date or
time separators (such as "yyyyMMddHHmm"), use the invariant culture
for the provider parameter and the widest form of each custom format
specifier. For example, if you want to specify hours in the format
pattern, specify the wider form, "HH", instead of the narrower form,
"H".
So in your case you probably should use approach suggested in John's answer - add "missing" zero and parse with wider date format "dd"
The problem here seems to be that d can be a one-digit or two-digit date, so the parser struggles to determine if "2102019" refers to the 2nd of November 2019, or the 21st of... and then it breaks. With delimiters, the parser is able to act more intelligently. It will happily parse "2-10-2019" using "d-MM-yyyy".
My suggested solution to your problem is to pad the string, and change your format string:
string dateToParse = "6092019";
string paddedDateToParse = dateToParse?.PadLeft(8, '0'); // 06092019
DateTime parsedDate = DateTime.ParseExact(paddedDateToParse, "ddMMyyyy", CultureInfo.InvariantCulture, DateTimeStyles.None);
Try it online
I'm really new to Regex, so I'm looking for a way to check if my string starts with a certain regex. I found this on the Internet, however, I can't make it work with a custom regex.
I need to know if a specific line starts with
3.3. XXX
which is how you format German date. So the regex doesn't need to look up only this, but possibly
17.4. XXX
in both cases, I need to know if the input string starts with a date (which can have two possible notations, as stated above). So, for both it'd return true, however, it wouldn't for this:
15G
(for example).
Which regex is good to go for this?
Regex is not good at parsing number ranges so it can get pretty messy https://stackoverflow.com/a/15504877/1383168
To check if a string is a valid date you can use DateTime.TryParseExact
string s = "17.4. XXX"; DateTime d;
if (DateTime.TryParseExact(s.Split(' ')[0], "d.M.",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.None, out d))
{
// matches
Debug.Print($"{d}"); // "4/17/2017 12:00:00 AM"
}
if you want a regex for detecting dd.mm type of date this your answer.
string testregex = "([0-2][0-9]|3[0-1]|[0-9])(.)(0[1-9]|1[0-2]|[0-9])(.)";
you can check any string to find match for this regex, Regex.IsMatch() returns true and statements in if block will execute.
string text="17.4 xxxxxx";
if (Regex.IsMatch(string test,testregex))
{
//do something
}
Hello im searching regular expression for money and date on C#. i want to accept any positive number only in the format of 0.00 and not with a , like 0,00. Also im searching and expression for date with the format of dd/mm/yyyy . Can anyone help me? thank you
I have update the code to this
System.Text.RegularExpressions;
csReleaseDate = txtReleaseDate.Text;
String dateRegex = #"^\\d{2}/\\d{2}/\\d{4}$";
if (Regex.IsMatch(csReleaseDate, dateRegex)) {
lblRequired.Text = "is working";
} else {
lblRequired.Text = "is now working"; }
but nothing cites on the page
You are better off using the TryParse methods of DateTime and Decimal.
With DateTime you can use TryParseExact to match the exact format, and with Decimal if the format is right you can check if the value is positive.
These are better options for validating that strings are representing those types.
Don't use regular expressions for such a small problem. Get the money with a statement like that:
decimal parsedMoney;
if (decimal.TryParse(stringToParse, out parsedMoney))
{
// Do something with the money
}
And similar with the date like that:
DateTime parsedDate;
if (DateTime.TryParse(stringToParse, out parsedDate))
{
// Do something with the date
}
Edit
If you really want to use regex, then use \A\d+\.\d{2}\Z for searching your money and \d{2}/\d{2}/\d{4} for searching the date in your expected format.
Any time I've needed a regular expression I've used this web site for it.
Regular Expression Library web site.
"^\\d{2}/\\d{2}/\\d{4}$"
for date I think.
I receive Date and time from CSV file
The received Date format is YYYYMMDD (string) (there is no ":" ,"-","/" to
separate Year month and date).
The received time format is HH:MM (24 Hour clock).
I have to validate both so that (example) (i) 000011990 could be invalidated for date (ii) 77:90 could be
invalidated for time.
The question is ,
Regular expression is the right candidate for do so (or) is there any other way to achieve
it?
You're looking for DateTime.TryParseExact:
string source = ...;
DateTime date;
if (!DateTime.TryParseExact(source,
"yyyyMMdd",
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date)) {
//Error!
}
You can use the same code to validate times, with the format string "HH:mm".
Your easiest solution would be to use
DateTime output;
if(!DateTime.TryParse(yourstring, out output))
{
// string is not a valid DateTime format
}
The DateTime.TryParse will attempt to convert your string to a DateTime variable, but it won't throw an exception if it fails - rather it return false if the string is not recognized as a valid DateTime.
I think a better way would be to use the date format class built into C#: DateTime.parse
You can use one of the TryParse methods of the DateTime struct. They will return false if they fail to parse.
Another option it use the ParseExact methods, but for those you need to specify a format provider.
I am trying to convert a string into datetime with the following C# code,
DateTime dTo = DateTime.ParseExact(dateTo, "mm/dd/yyyy", CultureInfo.InvariantCulture);
eachtime I pass dateTo as 1/1/2010 it fails, instead it needs the string to be 01/01/2010.
What string format should I use to support both 01/01/2010 and 1/1/2010?
Using the following date format expression will allow you to use either single or double digit day and month elements.
"M/d/yyyy"
Note that the capital M is significant - a lower case m is the placeholder for minutes.
You will find more information related to date format strings here.
You can use the following Powershell command to test them.
[DateTime]::ParseExact('01/01/2010', 'M/d/yyyy', $null)
Capital M is month, little m is mins i think.
But to the point of the question, use Parse. ParseExact implies you know the exact format of the input.
You could try this format: MM/dd/yyyy, but I think there's no single format string that could support both inputs. You could test if the length of your dateTo string is less than 10 characters use M/d/yyyy, otherwise MM/dd/yyyy.