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
}
Related
I have a string like below,
var text1 = "TEST 01DEC22 test";
I want to capture only the "01DEC22" date from the string; I tried and was successful if only the text contained the date only, as shown below.
var text = "01DEC22";
var results = Regex.Matches(text, #"^(([0-9])|([0-2][0-9])|([3][0-1]))(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d{2}$").Cast<Match>().Select(x => x.Value).FirstOrDefault();
Kindly help me how to retrieve the value if it is contained within a string.
If the dates are to be in two digits always, you may use below regex
((0[1-9])|([12]\d)|(3[01]))(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d\d
As stated in the comments just remove the ^ and $ but you seem to have a careful way of checking for the day of the month instead of just \d?\d but with your method you still accept 0DEC22 as a date.
You can simplify the regex to this which only accepts valid days of the month:
(0?[1-9]|[12]\d|3[01])(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d\d
This would be even simpler if you aren't worried about invalid dates:
(\d?\d)(JAN|FEB|MAR|APR|MAY|JUN|JUL|AUG|SEP|OCT|NOV|DEC)\d\d
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.
I’m trying to parse a time. I’ve seen this question asked/answered here many times but not for this specific scenario. Here’s my code:
var time1 = DateTime.ParseExact("919", "Hmm", CultureInfo.InvariantCulture);
also
var time2 = DateTime.ParseExact("919", "Hmm", null);
both of these throw the same
"String was not recognized as a valid DateTime"
What I want is 9:19 AM.
For further info I also need to parse “1305” as 1:05 PM, this is working fine.
It seems to me I’m using the correct format. What am I overlooking?
I'm not sure there is any format that can handle this. The problem is that "H" can be either one digit or two, so if there are two digits available, it will grab both - in this case parsing it as hour 91, which is clearly invalid.
Ideally, you'd change the format to HHmm - zero-padding the value where appropriate - so "0919" would parse fine. Alternatively, use a colon in the format, to distinguish between the hours and the minutes. I don't believe there's any way of making DateTime parse a value of "919" as you want it to... so you'll need to adjust the string somehow before parsing it. (We don't have enough context to recommend a particular way of doing that.)
Yes, your format is right but since H specifier might be 2 character, ParseExact method try to parse 91 as an hour, which is an invalid hour, that's why you get FormatException in both case.
I connected to microsoft team about this situation 4 months ago. Take a look;
DateTime conversion from string C#
They suggest to use 2 digit form in your string or insert a date separator between them.
var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);
or
var time1 = DateTime.ParseExact("9:19", "H:mm", CultureInfo.InvariantCulture);
You cant exclude the 0 prefix to the hour. This works
var time1 = DateTime.ParseExact("0919", "Hmm", CultureInfo.InvariantCulture);
Perhaps you want to just prefix 3-character times with a leading zero before parsing.
Much appreciated for all the answers. I don’t have control of the text being created so the simplest solution for me seemed to be prefixing a zero as opposed to adding a colon in the middle.
var text = "919";
var time = DateTime.ParseExact(text.PadLeft(4, '0'), "Hmm", null);
I know this question has been asked a number of different ways, and I have looked at them all and none of the solutions seem to work for me. So, I am hoping that maybe you guys can give me a quick hand.
The input string is: "2000-01-01T12:00:000Z". I need to take that input string and convert it to DateTime so that it can be stored in the database.
I have been using ParseExact, but I keep getting the not recognized date string exception. Where am I going wrong?
inValue.LatestDepartTime = "2000-01-01T12:00:000Z";
DateTime _latestDepartTime = DateTime.ParseExact(inValue.LatestDepartTime, "yyyy-MM-dd HH:mm:ss.fff", CultureInfo.InvariantCulture);
Your format string needs to exactly match the input.
That includes the literal T and Z characters.
Use yyyy-MM-dd'T'HH:mm:ss.fff'Z'
The code is:
public DateTime convertIsoToDateTime (string iso)
{
return DateTime.ParseExact(iso, "yyyy-MM-dd'T'HH:mm:ss.fff'Z'", CultureInfo.InvariantCulture);
}
You need to include \\T and \\Z in your format string to match the literals T and Z.
You need to put single quotes around the T and Z:
DateTime parsedDateTime;
DateTime.TryParseExact(obj, "yyyy-MM-dd'T'HH:mm:ss'Z'", null, System.Globalization.DateTimeStyles.None, out parsedDateTime);
return parsedDateTime;
You don't specify the T in the pattern.
That said, you may want to have a look at the XmlConvert class, which provides the methods for converting this format.
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.