1

Like many others, I'm crap at regex and particularly bad when it comes to regex in javascript.

I have a string that can take two formats:

var str = "This is a string t:1h"

or

var str = "This is a string t:1h,2h,3h"

I would like to match the 't:X' part or 't:X,X,X' part (whichever it happens to be) from the string and handle that separately.

Can anybody clever show me how to do a regex match on this string for this?

I haven't gotten very far. I have:

var reg = /\s?/m;
parsed = str.match(reg);

Please help.

4

2 回答 2

2

你的意思是这样吗?

var test = "This is a string t:1h,2h,3h"
var matches = test.match(/t:.*/)
console.debug(matches[0])

t:1h,2h,3h
于 2013-11-07T23:20:11.837 回答
2

这应该可以解决问题:

var str = "This is t:1h,2h,3h bla bla";
var reg = new RegExp("t:[0-9]h(,[0-9]h)*");
var parsed = str.match(reg)[0];

也可以使用 Javascript 的“special-RegExp-writing”:

var parsed = str.match(/t:[0-9]h(,[0-9]h)*/)[0];
于 2013-11-07T23:23:25.343 回答