我想使用正则表达式代码验证文本框中的文本,其中用户将被允许使用 6 位或 10 位数字,并在邮政编码的数字之间的任何位置使用符号 (-) 我无法使用以下方式实现数字限制/^(\d{6}|\d{10})$/
但无法应用可选符号
有人可以帮我把这个短路吗?
最佳答案
您可以先检查所需的长度,然后再检查内容。
/^ string start
(?=(.{7}|.{11})$) length check with positive look ahead
\d+-\d+ pattern check
$/ end of string
var test = [
'1',
'a',
'-',
'12',
'1245678901234567',
'1-23456',
'12-3456',
'123-456',
'1234-56',
'12345-6',
'12-345-6',
'12345-67890',
'foo-bar'
];
test.forEach(function (a) {
console.log(a, /^(?=(.{7}|.{11})$)\d+-\d+$/.test(a));
});
.as-console-wrapper { max-height: 100% !important; top: 0; }
关于javascript - 允许 6 位或 10 位数字并带有符号 (-) 的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41910038/