Performing a regex substitution Perl

后端 未结 4 1050
春和景丽
春和景丽 2021-01-27 17:41

Assuming I have the IP 10.23.233.34 I would like to simply swap the 233 for 234. The first, second, and last octet are unknown. The thir

4条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-27 18:01

    Sometimes regexes make things brittle and harder to understand. Nonetheless:

    my $ip = '10.23.233.34';
    ...
    for ($ip) {
        s!(?<=\.)233(?=\.\d+$)!234!;
    }
    

    Details: If given a well-formed dotted quad, the above looks for '233' in what must be the third octet: preceded by a dot and followed by a dot, then one or more digits, then end-of-string. The ?<= and ?= prevent anything other than the '233' from being captured, and then '234' is substituted. This approach does not validate that the IP address is well-formed.

提交回复
热议问题