简体   繁体   中英

Doing a regex match on a string in javascript

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.

You mean like this?

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

Gives

t:1h,2h,3h

This should do the trick:

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];

One could also use the "special-RegExp-writing" of Javascript:

var parsed = str.match(/t:[0-9]h(,[0-9]h)*/)[0];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM