简体   繁体   中英

Replace IP address from URI with another IP address using regex

String uri = "rtps://12.10.10.124/abc/12.10.22.10";

I'm trying to replace any first occurrence of IP address in this uri with let's say "127.0.0.1" using an efficient regex.
Taking into account that numbers with dots may be introduced in the uri at the end. The regex has to replace only the first occurrence of any IP-address in the URI.

Output would be:

uri = "rtps://127.0.0.1/abc/12.10.22.10";

s/[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}/127\\.0\\.0\\.1/

将字符串中第一次出现的ip地址转换为“127.0.0.1”

String ipRegex = "\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}";
String uri2 = uri.replaceFirst(ipRegex, "127.0.0.1");

This of course matches any 4 groups of 1-3 digits separated by 3 dots (eg: 999.999.999.999 will match), if you want something that matches only legal IP addresses, you could go for:

String ipRegex = "((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)";

But I personally think this is overkill.

String uri = uri.replaceFirst("\\d+\\.\\d+\\.\\d+\\.\\d+", "127.0.0.1");

In Java you can do it with the URL class.

URI u = new URI(uri);
u = new URI(u.getScheme(), "127.0.0.1", u.getPath(), u.getFragment());
uri = u.toString();

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