Regex匹配没有分号的mac地址

问题描述 投票:0回答:2

我试图理解为什么下面的函数返回奇怪的结果

<?
$string = "001122334 001122334455 0011 0011223344556677";
preg_match_all('/([a-fA-F0-9]){12}/', $str, $matches);
?>

我不知道为什么001122334455出现两次,为什么5 5在那里出现两次。我正在寻找没有半列匹配的MAC地址

输出

Array
( 
[0] => Array
    (
        [0] => 001122334455
        [1] => 001122334455
    )

[1] => Array
    (
        [0] => 5
        [1] => 5
    )
)
php regex
2个回答
0
投票

我认为您应该分析价值的空间终点。

$string = "001122334 001122334455 0011 0011223344556677";
preg_match_all('/([a-fA-F0-9]){12}\ /', $string, $matches);

0
投票

您的正则表达式

  • 包含一个重复捕获组([a-fA-F0-9]){12},即将一个十六进制字符捕获到一个组中,然后将该组的值重写11次以上(总共12次) ,因此最后一个十六进制字符在第二个匹配子数组中捕获了土地。
  • 没有固定在两侧,因此可以在字符串内的任何位置找到它,因此您将获得两个匹配项,001122334455被匹配,001122334455中的0011223344556677也被匹配。

删除捕获括号并使用整个单词匹配模式,例如

preg_match_all('/\b[a-fA-F0-9]{12}\b/', $str, $matches)            # Word boundaries
preg_match_all('/(?<!\S)[a-fA-F0-9]{12}(?!\S)/', $str, $matches)   # Whitespace boundaries
preg_match_all('/(?<![a-fA-F0-9])[a-fA-F0-9]{12}(?![a-fA-F0-9])/', $str, $matches) # Hex char boundaries

请参见PHP demo

© www.soinside.com 2019 - 2024. All rights reserved.