本文的正则表达式

时间:2016-06-28 11:26:05

标签: php regex

我想写一个regex来从以下文本中提取数字(这是更大文本的一部分):

 switchport trunk allowed vlan 206,220,23,234,250,262,21,283,2086,296,305,323
 switchport trunk allowed vlan add 334,340,342,365,380,404,41,414,42,421,434
 switchport trunk allowed vlan add 461,472,499,509,29,535,544,551,552,55,595
 switchport trunk allowed vlan add 642,672,690,697,701,704,711,800,2018,2020
 switchport trunk allowed vlan add 2054
 switchport mode trunk

我想提取 switchport trunk allowed vlan switchport mode trunk

之间的所有vlan号码

我认为模式应该像:

switchport trunk allowed vlan (\S*) ((\d+),*)+(?:.|\n)

但不知道如何提取其他数字(只有匹配的第一个数字)

我在PHP函数中使用preg_match中的模式。

2 个答案:

答案 0 :(得分:1)

要提取所有数字,您可以通过以下方式完成: -

<?php
$str = ' switchport trunk allowed vlan 206,220,23,234,250,262,21,283,2086,296,305,323
 switchport trunk allowed vlan add 334,340,342,365,380,404,41,414,42,421,434
 switchport trunk allowed vlan add 461,472,499,509,29,535,544,551,552,55,595
 switchport trunk allowed vlan add 642,672,690,697,701,704,711,800,2018,2020
 switchport trunk allowed vlan add 2054
 switchport mode trunk'; // original string
preg_match_all('!\d+!', $str, $matches); // check for all digits and make array $matches
print_r($matches); // print digits array
echo implode(',',$matches[0]); // convert digits array into comma separated string of numbers
?>

输出: - https://eval.in/596968https://eval.in/596974

注意: - 这也适用于单行,多行,段落(如果您的完整数据在单个变量中)。

答案 1 :(得分:1)

这将打印每个匹配,数组$ matches [0]具有所有值。

$str=' switchport trunk allowed vlan 206,220,23,234,250,262,21,283,2086,296,305,323
 switchport trunk allowed vlan add 334,340,342,365,380,404,41,414,42,421,434
 switchport trunk allowed vlan add 461,472,499,509,29,535,544,551,552,55,595
 switchport trunk allowed vlan add 642,672,690,697,701,704,711,800,2018,2020
 switchport trunk allowed vlan add 2054
 switchport mode trunk';

preg_match_all("/([0-9])\w+/", $str, $matches);
foreach ($matches[0] as $val) {
    echo $val.'<br>';
}