简体   繁体   中英

Regex to replace IP address

75.122.1.23

I need to replace the third number with 2 so it looks like 75.122.2.23

What regex can match the third section?

int replacementNumber = 2;
ip = ip.replaceAll("(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})\\.(\\d{1,3})", "$1.$2."+replacementNumber+".$4");

Commented form:

/^                 # match beginning
    (
        \d{1,3}    # one address segment
        \.         # separation dot
        \d{1,3})   # second address segment
    \.             # separation dot
    \d{1,3}        # address segment to be replaced
    \.             # separation dot
    (\d{1,3})      # last address segment
$/x                # match end, ignore comments
^([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.
([01]?\\d\\d?|2[0-4]\\d|25[0-5])\\.([01]?\\d\\d?|2[0-4]\\d|25[0-5])$ 

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