通过大列表中的特定掩码查找数字

时间:2018-04-24 07:52:44

标签: php regex

我有一个包含数字的大型列表。

如何找到特定面具的数字? (Regex + PHP)

示例必需掩码 AA* ХY YХ

118 75 57 - Ok
559 93 39 - Ok
777 25 56 - No
808 44 55 - No

A,X,Y,* - 任意数字0-9

数字长度始终为7个字符。

2 个答案:

答案 0 :(得分:2)

在PHP中,这将完成如下:

<?php

$data = [
'118 75 57',
'559 93 39',
'777 25 56',
'808 44 55'
];
$regex = '/(\d)\1\d (\d)(\d) \3\2/';
foreach($data as $str)
{
    echo preg_match($regex,$str) ? 'matched' : 'not matched',"<br>\n";
}

答案 1 :(得分:1)

让你自己熟悉(命名/未命名)反向引用:

^                      # start of the string
(?P<A>\d)\g{A}\d\s+    # AA*, whitespaces
(?P<X>\d)(?P<Y>\d)\s+  # XY, whitespaces
\g{Y}\g{X}             # YX
$                      # end of the string

请参阅a demo on regex101.com(并注意不同的修饰符,例如详细和多行)。

<小时/> 在PHP

<?php

$data = [
'118 75 57',
'559 93 39',
'777 25 56',
'808 44 55'
];

$regex = '~
        ^                      # start of the string
        (?P<A>\d)\g{A}\d\s+    # AA*, whitespaces
        (?P<X>\d)(?P<Y>\d)\s+  # XY, whitespaces
        \g{Y}\g{X}             # YX
        $                      # end of the string
~x';

foreach ($data as $item) {
    if (preg_match($regex, $item)) {
        echo "{$item} is valid\n";
    }
}
相关问题