[英]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. 像许多其他人一样,我对正则表达式很苛刻,尤其是在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. 我想匹配't:X'部分或't:X,X,X'部分(无论哪个恰好是)从字符串中单独处理。
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: 也可以使用Javascript的“special-RegExp-writing”:
var parsed = str.match(/t:[0-9]h(,[0-9]h)*/)[0];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.