You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Perl正则表达式匹配/etc/hosts中IP及对应主机名方案

匹配/etc/hosts中IP及关联主机名的正则表达式

需求

寻找能匹配/etc/hosts文件中指定IP对应的IP地址及其所有关联主机名的正则表达式。

示例hosts文件

10.10.10.10  test.com test2.com
10.10.10.11  test1.com 
10.10.10.12  test3.com test5.com

使用的正则表达式

^(\s+)?(?<Address>[0-9.:]+)(\s+(?<Host>[\w.-]+))+$

预期输出

Address: ["10.10.10.10"]
Host: ["test.com","test2.com"]

Address: ["10.10.10.11"]
Host: ["test1.com"]

Address: ["10.10.10.12"]
Host: ["test3.com","test5.com"]

Perl示例代码

use strict;
use Data::Dumper;

my @str = ( "10.10.10.10  test.com test2.com",
            "10.10.10.11  test1.com",
            "10.10.10.12  test3.com test5.com");

foreach ( @str  )
{
    while ($_ =~ m/^(\s+)?(?<Address>[0-9.:]+)(\s+(?<Host>[\w.-]+))+$/img) {
       print Dumper(\%+) ;
    }
}

内容的提问来源于stack exchange,提问作者EricStolz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 07:31:17