问题
I have file.txt which contains this data:
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)
I want to extract the IP of pc39.home. I have used this regular expression but it not work:
preg_grep("#^[a-z]{2}39.[a-z]{4} \d{3}\.\d{3}\.\d{1}\.\d{2}#",$myfile);
The result should be 192.168.1.15.
回答1:
with this you can just change the $search if you want to caputure any of the other IPs.
$search = "pc39\.home";
preg_match("/" . $search ." \(([\d.]+)\)/", $myfile, $out);
回答2:
You can use
preg_match('~^[a-z]{2}39\.[a-z]{4} \(([\d.]+)~m', $myfile_contents, $matches);
print_r($matches[1]);
See the regex demo
I added a \( to match a literal ( and used a capturing group around [\d.]+ (1 or more digits or dots) that matches the IP that can be retrieved using [1] index in $matches. The ~m enables a multiline mode so that ^ could match the beginning of a line, not just the string start.
UPDATE
If you need to create a dynamic regex with a literal string in it, you should think about using 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]);
}
You also need a single quoted literal in ' \(([\d.]+)\)/' since the \ must be literal \ symbols (yes, PHP resolves \ as a literal \ with non-existing escape sequences, but why put it to PHP?).
回答3:
the solution is:
$myfile = file('file.txt');
$search = "pc39\.home";
foreach ($myfile as $lineContent)
{
$lines=preg_match("/" . $search ." \(([\d.]+)\)/", $lineContent, $out);
echo($out[1]);
}
来源:https://stackoverflow.com/questions/37294578/regular-expression-to-match-ip-addresses