匹配IP地址的正则表达式

Regular expression to match IP addresses

我有 file.txt,其中包含以下数据:

livebox.home (192.168.1.1)
set-top-box41.home (192.168.1.10)
pc38.home (192.168.1.11)
pc43.home (192.168.1.12)
pc39.home (192.168.1.15)

我想提取pc39.home的IP。我已经使用了这个正则表达式,但它不起作用:

preg_grep("#^[a-z]{2}39.[a-z]{4} \d{3}\.\d{3}\.\d{1}\.\d{2}#",$myfile);

结果应该是192.168.1.15

你可以使用

preg_match('~^[a-z]{2}39\.[a-z]{4} \(([\d.]+)~m', $myfile_contents, $matches);
print_r($matches[1]);

regex demo

我添加了一个 \( 来匹配文字 ( 并在 [\d.]+ 周围使用了一个捕获组(1 个或更多数字或点 ) 匹配可以使用 $matches 中的 [1] 索引检索的 IP。 ~m 启用多行模式,以便 ^ 可以匹配行的开头,而不仅仅是字符串开头。

更新

如果您需要创建一个包含文字字符串的动态正则表达式,您应该考虑使用 preg_quote:

$myfile = file('file.txt');
$search = "pc39.home";           // <= a literal string, no pattern
foreach ($myfile as $lineContent)
{
     $lines=preg_match('/' . preg_quote($search, "/") . ' \(([\d.]+)\)/', $lineContent, $out);
     echo($out[1]);
}

您还需要在 ' \(([\d.]+)\)/' 中使用单引号文字,因为 \ 必须是文字 \ 符号(是的,PHP 将 \ 解析为带有不存在的转义序列的文字 \,但为什么要将其放入 PHP?)。

有了这个,如果您想捕获任何其他 IP,您只需更改 $search。

$search = "pc39\.home";
preg_match("/" . $search ." \(([\d.]+)\)/", $myfile, $out);

解决方法是:

$myfile = file('file.txt');
            $search = "pc39\.home";
            foreach ($myfile as $lineContent)
            {
               $lines=preg_match("/" . $search ." \(([\d.]+)\)/", $lineContent, $out);
               echo($out[1]);
            }