Reputation: 15
I can't for the life of me seem to figure out how to set a regular expression of an element with the formatting.
1d 5h 6m 12s
And also allow it to have any variation of those such as
1d
1d 1h
1d 1h 1m
1d 1s
6m 12s
etc...
Is it possible with regular expressions to do that tyle of formatting?
Upvotes: 1
Views: 424
Reputation: 9949
To give you a starting point:
(\d+d){0,1} //days - not checking for a max
(((([0-1]){0,1}\d)|(2[0-4]))h){0,1} // 24 hours
(((([0-5]){0,1}[0-9])|(60))m){0,1} //60 minutes
(((([0-5]){0,1}[0-9])|(60))s){0,1} //60 seconds
Then put them all together (in this case not worrying about amount of whitespace)
(\d+d){0,1}[ ]*(((([0-1]){0,1}\d)|(2[0-4]))h){0,1}[ ]*(((([0-5]){0,1}[0-9])|(60))m){0,1}[ ]*(((([0-5]){0,1}[0-9])|(60))s){0,1}[ ]*
Including @nhahtdh 's improved version of the above from the comments. Thanks!
((\d+)d)? *(([01]?\d|2[0-4])h)? *(([0-5]?\d|60)m)? *(([0-5]?\d|60)s)? *
Upvotes: 0
Reputation: 30293
Assuming you need it to be order,
if (/^\s*(?:(?:[1-9]\d*|0)d\s+)?(?:(?:1?\d|2[0-3])h\s+)?(?:[1-5]?\dm\s+)?(?:[1-5]?\ds)?\s*$/.test(str))
{
// success
}
Here's a quick breakdown:
The ^
and $
are known as anchors. They match the beginning and end of a string, so you're matching the entire string, not only a part, e.g. hello, world! 1d 5h 6m 12s
would pass otherwise.
The \s*
and \s+
match zero or more, and one or more, whitespace characters.
The (?:[1-9]\d*|0)
matches an arbitrary number of digits but not one that start with zero, unless it's exactly zero.
The (?:1?\d|2[0-3])
matches the digits between 0 and 23, inclusive.
The [1-5]?\d
matches the digits between 0 and 59, inclusive.
The (?: ... )
are known as non-capturing groups. They're like parentheses (for grouping) except that plain ol' parentheses capture, and we don't need that here.
The ?
means the preceding entity is optional.
Upvotes: 4
Reputation: 5491
I think this is what you want:
function parse(s) {
y = s.match(/(?:(\d+)d\s*)?(?:(\d+)h\s*)?(?:(\d+)m\s*)?(?:(\d+)s)?/);
console.log(y);
return y;
}
Here's how it works:
(\d+)d\s*
matches some digits followed by a d
, followed by optional whitespace(?:...)?
, like (?:(\d+)d\s*)?
makes the above optional. The ?:
causes the new set of parentheses to not be a capturing group.Upvotes: 0