简体   繁体   English

正则表达式替换IP地址

[英]Regex to replace IP address

75.122.1.23 75.122.1.23

I need to replace the third number with 2 so it looks like 75.122.2.23 我需要将第三个数字替换为2,这样看起来像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])$ 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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