Reputation: 117
A time string containing minutes and/or seconds looks like this
29m 15s
The delimiter is a single space. The numbers have no leading zeroes. Either the minutes or the seconds part (but not both) can be omitted. If one of them is missing, so is the delimiter. That is, the following are all valid examples of such time strings:
1m
47s
1m 15s
12m 4s
I need to construct a regular expression that would return in $1 and $2 the number of minutes and seconds respectively. I'm writing a JavaScript program, but it's constructing the regular expression that I have a problem with - not the actual programming.
Upvotes: 1
Views: 81
Reputation: 34628
This is more verbose than the other answers, but does enforce the space. Also, it ensures the numbers are no more than 2 characters long.
/^(?:(\d{1,2})m) (?:(\d{1,2})s)$|^(\d{1,2})[ms]$/
"13m 20s" //match
"13m" //match
"20s" //match
"13m20s" //no match
Upvotes: 0
Reputation: 16949
If i understand you correctly:
var s = '29m 15s';
var r = /(?:(\d+)m)?\s*(?:(\d+)s)?/;
var m = s.match(r);
This will produce array like this:
[ '29m 15s', '29', '15', index: 0, input: '29m 15s' ]
where m[1] is the minute and m[2] second(this one is optional)
Upvotes: 0
Reputation: 15552
This would match only the numbers in minutes and seconds:
/(?:(\d+)m)? ?(?:(\d+)s)?/
Upvotes: 1