简体   繁体   中英

Matching IP address in tcl without matching dotted strings

I'm trying to find all the IP addresses in a file and replace it with this pattern " * " but I end up matching dotted strings which look like IP addresses and replace/mangle them as well. Is there way out here? Maybe use tcl built in functions in the ip package?

The code looks something like this:

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 --> This should match

12.192.168.1.1.567 --> This should NOT match

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

如果要匹配192.168.1.1而不是12.192.168.1.1.567 ,则可以使用负数前瞻排除第二个匹配项。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM