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";
// this is the regex to validate an IP address. = zeroTo255 + "\\." + zeroTo255 + "\\."
The regular expression for valid IP addresses is : ((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]?)
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With