JavaScript RegExp to match a (partial) hour
I want to allow people to enter times into a textbox in various formats. One开发者_Go百科 of the formats would be either:
2h
for 2 hours, or
2.5h
for 2 and a half hours
I want to use a regex to recognise the pattern but it's not picking it up for some reason:
I have:
var hourRegex = /^\d{1,2}[\.\d+]?[h|H]$/;
which works for 2h
, but not for 2.5h
.
I thought that this regex would mean - Start at the beginning of the string, have one or two digits, then have none or one decimal points which if present must be followed by one or more digits then have a h
or a H
and then it must be the end of the string.
I have tried the regex tool here but no luck.
/^\d{1,2}(?:\.\d+)?h$/i;
Use parentheses instead of square braces.
- Start at the beginning
- One or two digits
- Optional: a dot followed by at least one digit
- End with a
h
- Case insensitive
RegExp tuturial
[...]
- square braces mean: anything which is within the provided range.[^...]
means: Match a character which is not within the provided range(...)
- parentheses mean: Group me. Optionally, the first characters of a group can start with:?:
- Don't reference me (me, I = group)?=
- Don't include me in the match, though I have to be here?!
- I may not show up at this point
{a,b}
,{a,}
means: At leasta
, maximumb
characters. Omittingb
= Infinity+
means: at least one time, match as much as possible equivalen to{1,}
*
means: match as much as possible equivalent to{0,}
+?
and*?
have the same effect as previously described, with one difference: Match as less as possible
Examples
[a-z] One character, any character between a, b, c, ..., z
(a-z) Match "a-z", and group it
[^0-9] Match any non-number character
See also
- MDN: Regular Expressions - A more detailed guide
The trouble is here :
[\.\d+]
you can not use character classes inside brackets.
Use this instead:
(\.[0-9]+)?
You've confused your square brackets with your parenthesis. Square brackets look for a single match of any contained character, whereas parenthesis look for a match of the entire enclosed pattern.
Your issue lies in [\.\d+]?
It's looking for .
or 0-9
or +
.
Instead you should try:
/^\d{1,2}(\.\d+)?(h|H)$/
Although that will still allow users to enter invalid numbers, such as 99.3
which is probably not the expected behavior.
精彩评论