作者:男人要走火_293 | 来源:互联网 | 2022-11-21 18:14
我需要检查字符串是否包含10000到1800000之间的数字.
我带来了以下正则表达式:
^[1-9][0-9]{4}$|^[0-9]{6}$|^1[0-7][0-9]{5}$|^1800000$+
是否有更好或更优化的方式来执行它?
const regex = /^[1-9][0-9]{4}$|^[0-9]{6}$|^1[0-7][0-9]{5}$|^1800000$/;
const mustFailTests = [
'9999',
'15',
'00015',
'-15000',
'1800001',
'9000000',
'0',
'',
];
const mustWorkTests = [
'10000',
'1800000',
'200000',
'25018',
'778410',
'1000000',
'1205900',
];
const start = Date.now();
mustFailTests.forEach((x) => {
const ret = regex.test(x);
console.log(`${x} must fail : result ${ret}`);
});
console.log('--------------------------------');
mustWorkTests.forEach((x) => {
const ret = regex.test(x);
console.log(`${x} must succeed : result ${ret}`);
});
for (let i = 0; i <500000; i += 1) {
mustWorkTests.forEach(x => regex.test(x));
mustFailTests.forEach(x => regex.test(x));
}
console.log(`It took ${Date.now() - start} ms`);
1> 小智..:
为什么不将该字符串转换为数字并与您需要的字符串进行比较
const validate = (input) => 10000 <= +input && 1800000 >= +input