【问题标题】:How to make Format ABC-1234 in regular Expressions如何在正则表达式中制作 ABC-1234 格式
【发布时间】:2017-09-08 11:19:56
【问题描述】:

我已经使用正则表达式完成了格式化:

<p class="phone">2124771000</p>
 $(".phone").text(function(i, text) {
        text = text.replace(/(\d\d\d)(\d\d\d)(\d\d\d\d)/, "$1-$2-$3");
        return text;
    });

使用上面的这个例子,我可以转换 212-477-1000:

<p class="phone">ABC1234</p>

现在我想用上面的文字制作 ABC-1234 字符串。

测试环境:http://jsfiddle.net/Xxk3F/4237/

【问题讨论】:

    标签: javascript php regex


    【解决方案1】:

    如果您想在 1 个正则表达式中同时捕获两者..

    您可以使用任一表达式|

    例如。

    /^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/

    function replacer(m, p1,p2,p3, p4,p5) {
      if (p1) return [p1,p2,p3].join('-')
      else return [p4,p5].join('-');
    }
    
    $(".phone").text(function(i, text) {
      text = text.replace(/^(\d{3})(\d{3})(\d{4})|([A-Z]{3})(\d{4})$/, replacer);
      return text;
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <p class="phone">ABC1234</p>
    <p class="phone">1231231234</p>
    <p class="phone">XYZ2345</p>
    <p class="phone">9999999999</p>

    【讨论】:

      【解决方案2】:

      以下将检查 3 个大写字母后跟 4 个数字:

      $(".phone").text(function(i, text) {
          text = text.replace(/([A-Z]{3})(\d{4})/, "$1-$2");
          return text;
      });
      

      【讨论】:

        【解决方案3】:

        你可以试试这个ABC1234:

        $(".phone").text(function(i, text) {
          text = text.replace(/([a-z]+(?=\d+))/i, "$1-");
          return text;
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <p class="phone">ABC1234</p>

        对于电话号码,试试这个:

        $(".phone").text(function(i, text) {
          text = text.replace(/(\d{3})(\d{3})(\d{4})/, "$1-$2-$3");
          return text;
        });
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        <p class="phone">2124771000</p>

        【讨论】:

          【解决方案4】:

          你可以试试这个模式

          text = text.replace(/([a-zA-Z]+)(\d+)/, "$1-$2");
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-03-21
            • 2011-10-30
            • 2016-08-09
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多