【问题标题】:How to write regex in JS for first 2 characters can be digit or alphabet and followed by hyphen and then 6 digit number?如何在 JS 中为前 2 个字符编写正则表达式,可以是数字或字母,后跟连字符,然后是 6 位数字?
【发布时间】:2020-01-13 11:13:20
【问题描述】:

我正在尝试为以下格式创建正则表达式:

12-345678  Matches
AB-345678  Matches

$12-345678 Failed
%%-SDdfdf  Failed
  1. 前 2 个字符应该是字母或数字,例如 AA 或 12
  2. 第三个字符必须是 -(连字符)和
  3. 最后六个字符应该是数字
  4. 字符串长度不应超过 9 个字符

我已经写了以下正则表达式,但它失败了:

$('#customer-number').keyup(function(){
$(this).val($(this).val().replace(/^(d{2}|[a-z]{2})\-\\d{6}/,'$1-'))
});

但正则表达式失败:

/^(d{2}|[a-z]{2})\-\\d{6}/

我是正则表达式的新手,请帮助我

【问题讨论】:

  • d\d 不同。 \\d 将匹配 \d 字符序列,而不是数字。 [a-z] 只匹配小写字母,你的意思是[A-Z] 还是[A-Za-z]?如果你想匹配整个字符串,你也会错过模式末尾的$。此外,正则表达式看起来像一个验证正则表达式,但您在 replace 方法中使用它,您能澄清一下吗?
  • 前 2 个字符是否允许使用 A11A
  • 其实不允许!

标签: javascript jquery regex


【解决方案1】:

您在d之前错过了\,您需要为大写添加A-Z,并且您添加了一个\来转义另一个\

^(\d{2}|[a-zA-Z]{2})\-\d{6}

演示:https://regex101.com/r/SEQGOq/1

【讨论】:

    【解决方案2】:

    试试这个正则表达式/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g

    function matchString() { 
            var test1 = "11-122121";
            var test2 = "1a-122121"; 
            var test3 = "aa-122121"; 
            var result1 = test1.match(/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g); 
            var result2 = test2.match(/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g); 
            var result3 = test3.match(/^([a-zA-Z]{2}|[0-9]{2})-\d{6}/g); 
            document.write("Output1 : " + result1 + "<br>");         
            document.write("Output2 : " + result2 + "<br>");
            document.write("Output3 : " + result3);
        } matchString();

    【讨论】:

      【解决方案3】:

      试试下面的

      /^[a-zA-Z0-9]{2}-\d{6}/
      

      在哪里

      ^ 在行首断言位置

      a-z a(索引 97)和 z(索引 122)之间的单个字符(区分大小写)

      A-Z 介于 A(索引 65)和 Z(索引 90)之间的单个字符(区分大小写)

      0-9 0(索引 48)和 9(索引 57)之间的单个字符(区分大小写)

      {2} 量词——精确匹配 2 次​​p>

      - 匹配字符 - 字面意思

      \d 匹配一个数字(等于 [0-9])

      {6} 量词——精确匹配 6 次

      演示:

      console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('12-345678'));  //true
      console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('AB-345678'));  //true
      console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('$12-345678')); //false
      console.log(/^[a-zA-Z0-9]{2}-\d{6}/.test('%%-SDdfdf'));  //false

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-08
        • 1970-01-01
        • 2012-07-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多