3 回答

TA貢獻1911條經(jīng)驗 獲得超7個贊
使用否定前瞻來防止00:00
特定情況:
^$|^(?!00:00$)(([01][0-9])|(2[0-3])):[0-5][0-9]$
演示: https: //regex101.com/r/jSKyZN/2

TA貢獻1796條經(jīng)驗 獲得超4個贊
00:00是一個特例。在運行正則表達式之前排除它,就是這樣。
if( thingToTest === "00:00" ){
return;
}
regexTime.test(thingToTest);

TA貢獻1820條經(jīng)驗 獲得超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
在使用否定之外進行匹配。這有點乏味,因為它使模式更大。盡管如此,了解以下內(nèi)容還是很有用的:
(([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])$
現(xiàn)在該模式明確匹配除 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中技術(shù)的名稱。它類似于使用否定前瞻,因為它允許您丟棄某些匹配項,但它僅使用 alternation 完成|
。你必須先添加你不想要的模式,然后|
最后使用捕獲組捕獲你想要的模式()
。
^$|^00:00$|^((?:[01][0-9]|2[0-3]):[0-5][0-9])$
請參閱 Regex101(00:00
突出顯示但未捕獲 - 請參閱右側(cè)的“匹配信息”)
我稍微修改了您的模式以刪除不需要的捕獲組,因此您最多只能獲得一次捕獲。這樣你就可以檢查它是否被提?。?/p>
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}]`);
}
這在這里有點矯枉過正,因為負前瞻可以做同樣的事情。我把它包括在這里主要是為了提高人們對它存在的認識。該技術(shù)在您只需要匹配某些情況而不是全部情況的其他情況下非常有用,因為它允許您“丟棄”您不喜歡的內(nèi)容并捕獲其余的內(nèi)容。這非常簡單,因為它遵循一個非常簡單的規(guī)則discard this|discard this, too|(keep this)
——任何你不想要的都添加在前面,你想要的模式在最后的捕獲組中。
使用代碼
您可以使用普通代碼而不是模式匹配來拒絕數(shù)據(jù)。
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}]`);
}
添加回答
舉報