1

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.

4

3 回答 3

1

这将仅匹配以分钟和秒为单位的数字:

/(?:(\d+)m)? ?(?:(\d+)s)?/
于 2012-06-14T11:28:56.643 回答
0

如果我理解正确:

var s = '29m 15s';
var r = /(?:(\d+)m)?\s*(?:(\d+)s)?/;
var m = s.match(r);

这将产生这样的数组:

[ '29m 15s', '29', '15', index: 0, input: '29m 15s' ]

其中 m[1] 是分钟和 m[2] 秒(这是可选的)

于 2012-06-14T11:27:50.387 回答
0

这比其他答案更冗长,但确实强制空间。此外,它确保数字长度不超过 2 个字符。

/^(?:(\d{1,2})m) (?:(\d{1,2})s)$|^(\d{1,2})[ms]$/

"13m 20s" //match
"13m" //match
"20s" //match
"13m20s" //no match
于 2012-06-14T11:40:18.070 回答