【发布时间】:2023-01-11 00:22:51
【问题描述】:
我想要一个特定的值,必须具有的值:
-
长度应为 11。
-
第一个数字应该是 0。
-
第二个数字应该是 1。
-
第三个数字应该是 0、1、2、5。
-
然后匹配从第四位到末尾的任何数字。
-
如果第三位是 1,那么最后两位(第 10、11)应该相同。
-
如果第三位是2,那么第8、9位应该相同。
输入字符串和预期结果。
01012345678 -----> allowed.
0101234a5678 -----> not allowed., letter exists.
01112345688 -----> allowed, 10th, 11st are the same
01112345677 -----> allowed, 10th, 11st are the same
01112345666 -----> allowed, 10th, 11st are the same
01112345689 -----> not allowed..10th, 11st different
01112345-678 -----> not allowed..hyphen exists.
01298765532 -----> allowed..8th, 9th are the same.
01298765732 -----> not allowed, 8th, 9th different.
01298765mm432 -----> not allowed, more than 11 chars.
01500011122 -----> allowed..
020132156456136 -----> not allowed..more than 11 digit.
01530126453333 -----> not allowed..more than 11 digit.
00123456789 -----> not allowed.. second digit.
这是我对 regex101 的尝试,^01[0125][0-9]{8}$https://regex101.com/r/cIcD0R/1 但它忽略了特定情况,它也适用于特定情况。
【问题讨论】:
-
我建议应该使用正则表达式来验证这一点,但是在一个正则表达式中执行所有操作将不可避免地导致非常脆弱(并且可能难以理解)的表达式;考虑为最终必须破译和更新相关代码的可怜人写作。
标签: javascript regex