问题描述
我只想存储接口名称。因此,在这种情况下,我想存储Interface900。下面是我的代码。似乎无法弄清楚该怎么做。
$str = '[TIMETRA-VRTR-MIB::vRtrIfName.22.178] => STRING: "interface900" ';
preg_match_all("!^STRING: \"?(.*?)\"?$!",$str,$matches))
print_r($matches);
也尝试过
preg_match_all('(STRING: ")([\w-_]*)',$matches);
print_r($matches);
在两种情况下,它都不会打印Interface900。我对正则表达式或PHP不太满意。有人可以帮我吗?
解决方法
您的RegEx不正确,应该是:
STRING: \"?(.*?)\"? $
STRING: \"? // Match the string 'STRING: ' followed by an optional double quote
(.*?) // Non-greedy capture anything until the next character in the pattern
\"? $ // Match an optional double quote followed by a space and the end of the string {$}
示例
preg_match_all("/STRING: \"?(.*?)\"? $/",$str,$matches);
print_r($matches);
/* Output:
Array
(
[0] => Array
(
[0] => STRING: "interface900"
)
[1] => Array
(
[0] => interface900
)
)
*/
preg_match("/STRING: \"?(.*?)\"? $/",$matches);
print_r($matches);
/* Output:
Array
(
[0] => STRING: "interface900"
[1] => interface900
)
*/
RegEx为什么失败
^STRING: \"?(.*?)\"?$
^ // Matches the start of the string {DOESN'T MATCH}
STRING: \"? // Match the string 'STRING: ' followed by an optional double quote
(.*?) // Non-greedy capture anything until the next character in the pattern
\"?$ // Match an optional double quote followed immediately by the end of the string {DOESN'T MATCH}
,
第二个模式在捕获组2中具有值。请注意,\w
也与下划线匹配。
没有捕获组的更精确的模式可能是声明结束"
并重复字符类至少1次以上以防止空匹配。
\bSTRING:\h+"\K[\w-]+(?=")
说明
-
\bSTRING:
匹配STRING:
-
\h+"
匹配1个以上水平空白字符和"
-
\K[\w-]+
重置匹配缓冲区,然后将一个字符或-
匹配1次以上 -
(?=")
正向前进,将"
直接声明为右侧
$re = '/\bSTRING:\h+"\K[\w-]+(?=")/';
$str = '[TIMETRA-VRTR-MIB::vRtrIfName.22.178] => STRING: "interface900" ';
preg_match_all($re,$matches);
print_r ($matches[0]);
输出
Array
(
[0] => interface900
)
匹配整个字符串,您还可以考虑前导方括号,并匹配1个以上的字符字符,然后可选地重复-
和1个以上的字符字符以防止仅匹配连字符。
您也可以使用捕获组,例如:
\[[^][]+\]\h+=>\h+STRING:\h+"(\w+(?:-\w+)*)"