3 回答

TA贡献1911条经验 获得超7个赞
使用否定前瞻来防止00:00
特定情况:
^$|^(?!00:00$)(([01][0-9])|(2[0-3])):[0-5][0-9]$
演示: https: //regex101.com/r/jSKyZN/2

TA贡献1796条经验 获得超4个赞
00:00是一个特例。在运行正则表达式之前排除它,就是这样。
if( thingToTest === "00:00" ){
return;
}
regexTime.test(thingToTest);

TA贡献1820条经验 获得超10个赞
正则表达式的“最小值”没有概念,因为它只是进行模式匹配,而不是推理模式代表什么。但是,您可以只排除某种模式不被匹配。如果您不想要00:00
,则可以将其从有效中删除。
负前瞻
修改正则表达式的最简单方法是使用语法添加否定先行(?!)
。如果你不想匹配,00:00
那么你可以说(?!00:00)
。然后你的正则表达式需要是:
^$|^(?!00:00)(([01][0-9])|(2[0-3])):[0-5][0-9]$
const regex = /^$|^(?!00:00)(([01][0-9])|(2[0-3])):[0-5][0-9]$/;
const times = [
"00:01",
"00:10",
"01:00",
"12:01",
"13:01",
"23:59",
"00:00",
"23:60",
"24:00",
];
for (const time of times) {
test(time, regex);
}
function test(time, regex) {
const result = regex.test(time);
console.log(`result for [${time}] is [${result}]`);
}
不匹配的模式
您也可以制作您的模式以避免00:00
在使用否定之外进行匹配。这有点乏味,因为它使模式更大。尽管如此,了解以下内容还是很有用的:
(([01][0-9])|(2[0-3])):[0-5][0-9]
将匹配任何东西,为了避免00:00
你必须非常明确地指定任何东西而不是匹配它的模式:
^$|^(00:0[1-9]|00:[1-5][0-9]|0[1-9]:[0-5][0-9]|(1[0-9]|2[0-3]):[0-5][0-9])$
现在该模式明确匹配除 00:00
. 如您所见,它读起来更长更烦人。我不推荐它,但它有时很有用。
const regex = /^$|^(00:0[1-9]|00:[1-5][0-9]|0[1-9]:[0-5][0-9]|(1[0-9]|2[0-3]):[0-5][0-9])$/;
const times = [
"00:01",
"00:10",
"01:00",
"12:01",
"13:01",
"23:59",
"00:00",
"23:60",
"24:00",
];
for (const time of times) {
test(time, regex);
}
function test(time, regex) {
const result = regex.test(time);
console.log(`result for [${time}] is [${result}]`);
}
最好的正则表达式技巧
这是文章The Best Regex Trick中技术的名称。它类似于使用否定前瞻,因为它允许您丢弃某些匹配项,但它仅使用 alternation 完成|
。你必须先添加你不想要的模式,然后|
最后使用捕获组捕获你想要的模式()
。
^$|^00:00$|^((?:[01][0-9]|2[0-3]):[0-5][0-9])$
请参阅 Regex101(00:00
突出显示但未捕获 - 请参阅右侧的“匹配信息”)
我稍微修改了您的模式以删除不需要的捕获组,因此您最多只能获得一次捕获。这样你就可以检查它是否被提取:
const regex = /^$|^00:00$|^((?:[01][0-9]|2[0-3]):[0-5][0-9])$/;
const times = [
"00:01",
"00:10",
"01:00",
"12:01",
"13:01",
"23:59",
"00:00",
"23:60",
"24:00",
];
for (const time of times) {
test(time, regex);
}
function test(time, regex) {
const match = regex.exec(time);
const result = Boolean(match && match[1]);
// ^^ you can use the ?? operator for most newer environments *
console.log(`result for [${time}] is [${result}]`);
}
这在这里有点矫枉过正,因为负前瞻可以做同样的事情。我把它包括在这里主要是为了提高人们对它存在的认识。该技术在您只需要匹配某些情况而不是全部情况的其他情况下非常有用,因为它允许您“丢弃”您不喜欢的内容并捕获其余的内容。这非常简单,因为它遵循一个非常简单的规则discard this|discard this, too|(keep this)
——任何你不想要的都添加在前面,你想要的模式在最后的捕获组中。
使用代码
您可以使用普通代码而不是模式匹配来拒绝数据。
const regex = /^$|^(([01][0-9])|(2[0-3])):[0-5][0-9]$/;
const times = [
"00:01",
"00:10",
"01:00",
"12:01",
"13:01",
"23:59",
"00:00",
"23:60",
"24:00",
];
for (const time of times) {
test(time, regex);
}
function test(time, regex) {
let result = false;
if (time != "00:00") {
result = regex.test(time);
}
console.log(`result for [${time}] is [${result}]`);
}
添加回答
举报