首页 > 解决方案 > Pregex 不匹配正确的模式

问题描述

当我尝试将字符串与正则表达式匹配时,它不起作用。但是我认为正则表达式规则对我的知识来说很好。谁能帮我确定我的表达中缺少什么。

样品匹配

  1. HAD-ORAAS0001545-ORBTD0003457
  2. HAD-ORBTD0001545-ORAAS0003457
<?php
print_r((preg_match('/^HAD-OR[AAS,BTD][0-9]{5,7}$/','HAD-ORBTD0009999',$m)));
?>

标签: phpregexpreg-match-all

解决方案


使用您显示的示例,您能否尝试以下操作。在线正则表达式演示:在线正则表达式演示

^HAD(?:-OR(?:AAS|BTD)[0-9]{5,7}){1,2}$

说明:为上述添加详细说明。

^HAD                     ##Checking if it starts with HAD.
(?:                      ##Starting non capturing group from here.
-OR                      ##Matching -OR string here.
(?:                      ##Starting a non-capturing group here.
AAS|BTD                  ##Matching either AAS OR BTD here.
)                        ##Closing non-capturing group here.
[0-9]{5,7}               ##Putting digits should come with occurrences of 5 to 7 here.
)                        ##Closing very first non capturing group here.
{1,2}$                   ##Mentioning that either it should be 1 or 2 occurrences of whole first non capturing group.

推荐阅读