开发者

Replace IP address from URI with another IP address using regex

String uri = "rtps://1开发者_运维知识库2.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";


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.


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

transforms the first occurence of an ip address in a string to "127.0.0.1"


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();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜