问题
I've just tried several hundreds (if not thousands...) of RegEx's available to get what I want... But none of them worked.
I'm simply looking for a Regular expression, that represents a TimeSpan days.hours:minutes:seconds
:
7.00:00:00 would represent "7 Days"
This one sadly doesn't work:
(\d\d).(\d\d):(([0-6][0])|([0-5][0-9])):(([0-6][0])|([0-5][1-9]))
回答1:
That's because your Regex pattern is expecting 2 digits for days and you only have 1 digit. Just make the first digit optional with ?
(\d?\d)\.(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9]))
or better yet just use + to match one or more because that pattern would still not match 100 days
(\d+)\.(\d\d):(60|([0-5][0-9])):(60|([0-5][0-9]))
回答2:
The accepted answer doesn't seem to work for the basic case.
Following the TimeSpan parsing rule I have come up with this pattern.
^((?:-?0*\d+\.)?(?:0*)(?:2[0-3]|1[0-9]|[0-9]))(?::0*([0-5]?[0-9]))?(?::0*((?:[0-5]?[0-9])(?:\.\d{0,7})?))?$
Note This pattern will pass the 10.12
format while MSDN marks this as an invalid format. This should be a valid format IMO.
回答3:
This one is technically more correct and probably more efficient too:
\d+\.((0?\d)|(1\d)|(2[0-3]))(:[0-5]\d){2}
回答4:
This one worked pretty well for me.
^(\d{1,2}|\d\.\d{2}):([0-5]\d):([0-5]\d)(\.\d+)?$
Here are the validation results for different inputs.
+-----------------------+-------+
| Input | Valid |
+-----------------------+-------+
| 1.10:14:15.1 | True |
+-----------------------+-------+
| .10:14:15.1 | False |
+-----------------------+-------+
| 1.10:14:15. | False |
+-----------------------+-------+
| 1.10:14:15.123haha456 | False |
+-----------------------+-------+
| 10:14:15.1 | True |
+-----------------------+-------+
| 100:14:15.1 | False |
+-----------------------+-------+
| 6:14:15.1 | True |
+-----------------------+-------+
| :14:15.1 | False |
+-----------------------+-------+
| 00:14:15 | True |
+-----------------------+-------+
来源:https://stackoverflow.com/questions/12438861/timespan-regex-with-days-portion