序列号验证的正则表达式

时间:2016-02-23 12:46:41

标签: regex oracle validation

我需要为序列号验证编写正则表达式。 序列号可以是两种类型

  1. AA.BB.CCC其中A,B和C是0到9之间的数字
  2. AA.BB.CC.DDD.EEE.FF.GGGH其中A,B,C,D,E,F和G是数字,H是字符,AA.BB.CC.DDDAA.BB.CC.DDD.EEEAA.BB.CC.DDD.EEE.FF和{ {1}} 也是有效的。
  3. 实施例: AA.BB.CC.DDD.EEE.FF.GGG

    01.01.001 - valid 01.01.01.001 - valid 01.01.01.001.001 - valid 01.01.01.001.001.01 -valid 01.01.01.001.001.01.001 -valid 01.01.01.001.001.01.001a -valid

    目前我使用两个正则表达式 01.01.01.001.01 - invalid 01.01.01.001.001a -invalid 01.01.01.001.01.001 -invalid 01.01.01.001.01.001a -invalid 01.01.01.001.001.001 - invalid 01.01.01.001.001.001a - invalid'(\d{2}\.){3}\d{3}((\.\d{3})((\.\d{2})(\.\d{3}(\w)?)?)?)?$'

    有没有办法将这两者结合在一起?

2 个答案:

答案 0 :(得分:2)

您真的可以使用| alternation operator加入这两个正则表达式,但您还需要相应地group

^((\d{2}\.){3}\d{3}((\.\d{3})((\.\d{2})(\.\d{3}(\w)?)?)?)?|(\d{2}\.){2}\d{3})$
^^                                                        ^^                ^

请参阅regex demo。不要忘记^ / $锚点,以确保整个字符串符合模式。

答案 1 :(得分:1)

您可以在一个正则表达式中完成所有操作:

^\d\d\.\d\d\.\d\d(\d|\.\d{3}(\.\d{3}(\.\d\d(\.\d{3}[A-H]?)?)?)?)$

然后,您始终可以提取捕获组以获取序列号组件:

CREATE TABLE serial_numbers ( serial_number ) AS
SELECT '01.02.03'                 FROM DUAL UNION ALL
SELECT '01.02.003'                FROM DUAL UNION ALL
SELECT '01.02.03.004'             FROM DUAL UNION ALL
SELECT '01.02.03.004.005'         FROM DUAL UNION ALL
SELECT '01.02.03.004.005.06'      FROM DUAL UNION ALL
SELECT '01.02.03.004.005.06.007'  FROM DUAL UNION ALL
SELECT '01.02.03.004.005.06.007A' FROM DUAL;

SELECT serial_number,
       REGEXP_SUBSTR( serial_number, '^(\d\d)', 1, 1, NULL, 1 ) AS AA,
       REGEXP_SUBSTR( serial_number, '^\d\d\.(\d\d)', 1, 1, NULL, 1 ) AS BB,
       REGEXP_SUBSTR( serial_number, '^\d\d\.\d\d\.(\d\d\d?)', 1, 1, NULL, 1 ) AS CCC,
       REGEXP_SUBSTR( serial_number, '^\d\d\.\d\d\.\d\d\.(\d{3})', 1, 1, NULL, 1 ) AS DDD,
       REGEXP_SUBSTR( serial_number, '^\d\d\.\d\d\.\d\d\.\d{3}\.(\d{3})', 1, 1, NULL, 1 ) AS EEE,
       REGEXP_SUBSTR( serial_number, '^\d\d\.\d\d\.\d\d\.\d{3}\.\d{3}\.(\d\d)', 1, 1, NULL, 1 ) AS FF,
       REGEXP_SUBSTR( serial_number, '^\d\d\.\d\d\.\d\d\.\d{3}\.\d{3}\.\d\d\.(\d{3})', 1, 1, NULL,  1 ) AS GGG,
       REGEXP_SUBSTR( serial_number, '^\d\d\.\d\d\.\d\d\.\d{3}\.\d{3}\.\d\d\.\d{3}([A-H])', 1, 1, NULL,  1 ) AS H
FROM   serial_numbers
WHERE  REGEXP_LIKE( serial_number, '^\d\d\.\d\d\.\d\d(\d|\.\d{3}(\.\d{3}(\.\d\d(\.\d{3}[A-H]?)?)?)?)$' );

<强>输出

SERIAL_NUMBER            AA BB CCC DDD EEE FF GGG H
------------------------ -- -- --- --- --- -- --- -
01.02.003                01 02 003                  
01.02.03.004             01 02 03  004              
01.02.03.004.005         01 02 03  004 005          
01.02.03.004.005.06      01 02 03  004 005 06       
01.02.03.004.005.06.007  01 02 03  004 005 06 007   
01.02.03.004.005.06.007A 01 02 03  004 005 06 007 A