perl正则表达式匹配n位数,但仅限于它们不完全相同

 平凡快乐的girl_819 发布于 2023-02-08 13:55

使用Perl正则表达式,我需要匹配一系列八位数,例如12345678,但前提是它们并非完全相同.00000000和99999999是不匹配的典型模式.我试图从现有的数据库记录中清除掉明显无效的值.

我有这个:

my ($match) = /(\d{8})/;

但我不能完全正确地安排背反射.

1 个回答
  • 怎么样:

    ^(\d)(?!\1{7})\d{7}$
    

    这将匹配没有8个相同数字的8位数字.

    示例代码:

    my $re = qr/^(\d)(?!\1{7})\d{7}$/;
    while(<DATA>) {
        chomp;
        say (/$re/ ? "OK : $_" : "KO : $_");
    }
    
    __DATA__
    12345678
    12345123
    123456
    11111111
    

    输出:

    OK : 12345678
    OK : 12345123
    KO : 123456
    KO : 11111111
    

    说明:

    The regular expression:
    
    (?-imsx:^(\d)(?!\1{7})\d{7}$)
    
    matches as follows:
    
    NODE                     EXPLANATION
    ----------------------------------------------------------------------
    (?-imsx:                 group, but do not capture (case-sensitive)
                             (with ^ and $ matching normally) (with . not
                             matching \n) (matching whitespace and #
                             normally):
    ----------------------------------------------------------------------
      ^                        the beginning of the string
    ----------------------------------------------------------------------
      (                        group and capture to \1:
    ----------------------------------------------------------------------
        \d                       digits (0-9)
    ----------------------------------------------------------------------
      )                        end of \1
    ----------------------------------------------------------------------
      (?!                      look ahead to see if there is not:
    ----------------------------------------------------------------------
        \1{7}                    what was matched by capture \1 (7 times)
    ----------------------------------------------------------------------
      )                        end of look-ahead
    ----------------------------------------------------------------------
      \d{7}                    digits (0-9) (7 times)
    ----------------------------------------------------------------------
      $                        before an optional \n, and the end of the
                               string
    ----------------------------------------------------------------------
    )                        end of grouping
    ----------------------------------------------------------------------
    

    2023-02-08 13:58 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有