正则表达式允许6位数或10位数字带符号( - )

时间:2017-01-28 12:57:23

标签: javascript jquery regex

我想使用正则表达式代码验证文本框中的文本,其中用户将被允许带有符号( - )的6位数或10位数邮政编码的数字之间的任何位置我能够使用正确的数字限制/^(\d{6}|\d{10})$/但无法应用可选符号

有人可以帮我解决这个问题。

3 个答案:

答案 0 :(得分:1)

您可以先检查所需长度,然后检查内容。

/^                                 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; }

答案 1 :(得分:0)

这个正则表达式使破折号可选:

var test = [
        '12456789',
        '12345678901',
        '123456',
        '1234567890',
        '1-23456',
        '12-34567890',
    ];

console.log(test.map(function (a) {
  return a+' : '+/^(?:(?:(?=.{7}$|.{11}$)\d+-\d+)|\d{6}|\d{10})$/.test(a);
}));

答案 2 :(得分:0)

根据@vickey评论,它实现了他的格式“12345-1234”

[0-9]{1,5}-[0-9]{1,4}

http://jsfiddle.net/5PNcJ/239/

相关问题