【发布时间】:2022-01-24 17:22:45
【问题描述】:
非常努力地尝试正则表达式,但无法获得所需的结果。
- 必须以数字开头,最多 4 个
- 后面只有一个允许的字母
请看下面的代码。
var strings = [
'1h', //should match
'13s', //should match
'30m', //should match
'42hr', //should not match
'8 hours ', //should not match
'765765', //should not match
'5sec', //should not match
'23445345345s', //should not match
'335m' //should match
];
for (var i = 0; i < strings.length; i++)
{
var match = strings[i].match(/\d{4}[h|m|s]{1}/g);
console.log(strings[i], (match ? "Match" : "Not match"));
}
【问题讨论】:
-
"必须以数字开头,最多为 4":那么你需要
{1,4},而不仅仅是{4}。对于字符组,不要使用|,所以使用[hms]。 -
@AndrewMorton 试过了。 5sec 和 23445345345s 不应匹配。但它正在匹配。
-
糟糕,我的意思是请查看 regex101.com/r/lMlyFS/1 以查看
/^[0-9]{1,4}[hms]$/gm是否有效。
标签: javascript node.js regex