在tcl中匹配IP地址而不匹配虚线字符串

时间:2013-11-08 10:18:28

标签: regex ip tcl

我正在尝试查找文件中的所有IP地址并将其替换为此模式“ * ”,但我最终匹配看起来像IP地址的虚线字符串并将其替换/修改为好。有出路吗?也许在ip包中使用tcl内置函数?

代码看起来像这样:

proc hide_ip { in_file } \
{
    set input_file [open $in_file]
    set file_content [read $input_file]
    set changed false 


    set ip_tags [list {(((25[0-5])|(2[0-4]\d)|(1\d\d)|(0?\d?\d))\.((25[0-5])|(2[0-4]\d)|(1\d\d)|(0?\d?\d))\.((25[0-5])|(2[0-4]\d)|(1\d\d)|(0?\d?\d))\.((25[0-5])|(2[0-4]\d)|(1\d\d)|(0?\d?\d))(/((3[0-2])|([1-2]?\d)))?)} \
                      {(((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?(/((12[0-8])|(1[0-1]\d)|(0?\d?\d)))?)}]

foreach item $ip_tags {
        set substituted [regsub -all -line -- $item $file_content {***} file_content]
        set changed [expr {$changed || $substituted}]
    }

...

192.168.1.1 - >这应该匹配

12.192.168.1.1.567 - >这不应该匹配

2 个答案:

答案 0 :(得分:1)

您可以使用\b标记正则表达式的边界,使其与12.192.168.1.1.567

中的内容不匹配

答案 1 :(得分:0)

如果您想匹配192.168.1.1而不是12.192.168.1.1.567,则可以使用否定前瞻来排除第二场匹配。