Regex with time

T

tony

Hello!

I have a time string from a TextBox that I want to validate to make
sure it's a valid time.
I found this snippet on the net below but it doesn't work because when
the method checktime.IsMatch is validating the passed string it return
false despite that the passed string is within valid bounds.
According to the information about the snippet that I found it
says that this regular expression checks the input for 00:00 to 23:59
is a valid time format.


private void IsValidTime()
{
string time = "10:35";
Regex checktime = new Regex(@"^(20|21|22|23|[01]d|d)(([:]
[0-5]d){1,2})$");
bool check = checktime.IsMatch(time);
}

So why does the checktime.IsMatch(time); return false when the string
is within valid bound.

//Tony
 
A

Alexander Mueller

tony said:
Hello!

I have a time string from a TextBox that I want to validate to make
sure it's a valid time.
I found this snippet on the net below but it doesn't work because when
the method checktime.IsMatch is validating the passed string it return
false despite that the passed string is within valid bounds.
According to the information about the snippet that I found it
says that this regular expression checks the input for 00:00 to 23:59
is a valid time format.


private void IsValidTime()
{
string time = "10:35";
Regex checktime = new Regex(@"^(20|21|22|23|[01]d|d)(([:]
[0-5]d){1,2})$");
bool check = checktime.IsMatch(time);
}

So why does the checktime.IsMatch(time); return false when the string
is within valid bound.


Because the the 'd'-characters in your pattern are literal d's,
not escaped symbols for 'digit':



new Regex(@"^(20|21|22|23|[01]\d|\d)(([:][0-5]\d){1,2})$");


does the trick

MfG,
Alex
 
P

Peter Duniho

I have a time string from a TextBox that I want to validate to make
sure it's a valid time.

Alex has explained your error. I will suggest that if you want to make
sure a string is a valid time, you should simply attempt to parse it and
let DateTime deal with whether it's valid or not.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top